一、冒泡排序
function swap(array, index1, index2) {
[array[index1], array[index2]] = [array[index2], array[index1]];
}
function sort(array) {
const len = array.length;
for (let i = 0; i < len; i++) {
let min = j;
for (let j = i + 1; j < len; j++) {
if (array[j] < array[i]) {
min = j;
}
swap(array, i, min);
}
}
return array;
}
二、插入排序
function sort(array) {
const len = array.length;
for (let i = 0; i < len; i++) {
for (let j = i; j > 0 && array[j] < array[j-1]; j--) {
swap(array, j, j - 1);
}
}
return array;
}
三、快速排序
function swap(nums, index1, index2) {
[nums[index1], nums[index2]] = [nums[index2], nums[index1]];
}
function paration(nums, start, end) {
const random = Math.floor(Math.random() * (end - start + 1)) + start;
swap(nums, random, end);
let small = start - 1;
for (let i = start; i <= end; i++) {
if (nums[i] < nums[end]) {
small++;
swap(nums, i, small);
}
}
small++;
swap(nums, small, end);
return small;
}
function quickSort(nums, start, end) {
if(start < end) {
const privot = paration(nums, start, end);
quickSort(nums, start, privot - 1);
quickSort(nums, privot + 1, end);
}
return nums;
}
function sort(nums) {
return quickSort(nums, 0, nums.length - 1);
}