//选择排序
function findMaxInde(arr, n) {
var max = 0;
var index = 0;
for (var i = 0; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
index = i; //记录最大值的索引号
}
}
return index
}
function selectionP(arr, n) {
while (n > 1) {
var index = findMaxInde(arr, n);
var t = arr[index];
arr[index] = arr[n - 1]; //将最大值与数组最后一位数进行交换
arr[n - 1] = t;
n--; //依次从后面由大到小排序
}
console.log(arr)
}
var arr = [1, 5, 4, 9, 8, 7, 6, 3]
selectionP(arr, 8)
//插入排序
function insert(arr, n) {
var index = n;
var key = arr[n];
while (arr[index - 1] > key) {
arr[index] = arr[index - 1];
index--; //前移
if (index == 0) { //到零停下
break;
}
}
arr[index] = key;
}
function SortInsert(arr, n) {
for (var i = 1; i < n; i++) {
insert(arr, i)
}
}
var arr2 = [8, 5, 9, 1, 4, 3, 6];
SortInsert(arr2, 7);
console.log(arr2)
//冒泡排序
function bubble(arr, n) {
var t;
for (var i = 0; i < n; i++) {
if (arr[i] > arr[i + 1]) {
t = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = t;
}
}
}
function bubbleSort(arr, n) {
for (var i = n; i >= 1; i--) {
bubble(arr, i);
}
}
var list = [1, 5, 6, 8, 9, 4];
//快速排序
function quickSort(list) {
if (list.length == 0 || list.length == 1) { return list }
var index = Math.floor(list.length / 2);
var cur = list.splice(index, 1);
var left = [];
var right = [];
list.forEach(item => {
if (item <= cur) {
left.push(item);
} else {
right.push(item);
}
})
return quickSort(left).concat(cur).concat(quickSort(right))
}
console.log(quickSort(list));
|