冒泡排序
function paixu(ArrayList) {
var arr = ArrayList;
for (var i = arr.length - 1; i >= 0 ; i--) {
for (var j = 0; j < i; j ++) {
if (arr[j] > arr[j + 1]) {
var tem = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tem
}
}
}
console.log(arr)
}
var arr = [7, 88, 4, 8, 66, 100, 77, 200, 67];
paixu(arr);
插入排序
function insertionSort(arr) {
var len = arr.length;
var preIndex, current;
for (var i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while (preIndex >= 0 && arr[preIndex] > current){
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr;
}
var arr1 = [7, 88, 4, 8, 66, 100, 77, 200, 67];
console.log(insertionSort(arr1));
快速排序
function quickSort(arr) {
if (arr.length == 0) {
return arr;
}
let middIndex = Math.floor(arr.length / 2);
let midd = arr.splice(middIndex, 1)[0];
let left = [],
right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > midd) {
right.push(arr[i]);
} else {
left.push(arr[i]);
}
}
return quickSort(left).concat(midd, quickSort(right));
}
let arr2 = [7, 88, 4, 8, 66, 100, 77, 200, 67];
console.log(quickSort(arr2));