选择排序
function _selectionSort(arr) {
let temp;
for (var i = 0; i < arr.length - 1; i++) {
let idx = i;
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[idx]) {
idx = j
}
}
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = temp
}
console.log(arr)
}
a = [6, 3, 1, 7, 8, 2, 4]
_selectionSort(a)
冒泡排序
function _bubbleSort(arr) {
let len = arr.length
for (var i = 0; i < len - 1; i++) {
for (var j = 0; j < len - 1; j++) {
if (arr[j] > arr[j + 1]) {
let t = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = t
}
}
}
console.log(arr)
}
a = [3, 1, 2, 4]
_bubbleSort(a)
快速排序
var a = [6, 3, 1, 2, 5, 4];
function _paritition(nums, l, r) {
let pivot = nums[l];
while (l < r) {
while (l < r && nums[r] >= pivot) {
r--;
}
nums[l] = nums[r];
while (l < r && nums[l] <= pivot) {
l++;
}
nums[r] = nums[l];
}
nums[l] = pivot;
return l;
}
function quickSort(nums, l, r) {
if (l < r) {
let middle = _paritition(nums, l, r);
quickSort(nums, l, middle - 1);
quickSort(nums, middle + 1, r);
}
return nums;
}
var res = quickSort(a, 0, 5);
console.log(res);
快速排序(PHP)
$a = [1, 6, 2, 7, 9, 3, 4, 5, 10, 8];
function qsort($nums)
{
if (count($nums) <= 1) {
return $nums;
}
$_left = [];
$_right = [];
$middle = $nums[0];
$len = count($nums) - 1;
for ($i = $len; $i > 0; $i--) {
if ($nums[$i] > $middle) {
array_push($_right, $nums[$i]);
} else {
array_push($_left, $nums[$i]);
}
}
$_left = qsort($_left);
$_left[] = $middle;
$_right = qsort($_right);
return array_merge($_left, $_right);
}
|