冒泡排序
function bubbleSort(array) {
let length = array.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
let temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
return array;
}
选择排序
function selectSort(array) {
let length = array.length;
let postion = 0;
let temp;
for (let i = 0; i < length; i++) {
postion = i;
for (let j = i; j < length; j++) {
if (array[j] > array[postion]) {
postion = j;
}
}
if (i !== postion) {
temp = array[i];
array[i] = array[postion];
array[postion] = temp;
}
}
return array;
}
插入排序
function insertionSort(array) {
let length = array.length;
for (let i = 1; i < length; i++) {
let temp = array[i];
let j = i;
for (let k = i - 1; k >= 0; k--) {
if (array[k] < temp) {
array[k + 1] = array[k];
j = k;
}
}
array[j] = temp;
}
}
function insertionSort(array) {
let length = array.length;
for (let i = 1; i < length; i++) {
let temp = array[i];
let j = i;
while (j > 0 && array[j - 1] < temp) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
console.log(array);
}
}
归并排序
function mergeSort(items) {
if (items.length === 1) {
return items;
}
let middle = Math.floor(items.length / 2);
let left = items.slice(0, middle);
let right = items.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
let result = [];
let il = 0;
let ir = 0;
while (il < left.length && ir < right.length) {
if (left[il] < right[ir]) {
result.push(left[il++]);
} else {
result.push(right[ir++]);
}
}
while (il < left.length) {
result.push(left[il++]);
}
while (ir < right.length) {
result.push(right[ir++]);
}
return result;
}