let array = createNonSortedArray(7);
array = bubbleSort(array);
console.log(array);
- 选择排序 复杂度O(N2)
function createNonSortedArray(size) {
const array = [];
for (let i = size; i > 0; i–) {
array.push(i);
}
return array;
}
function selectionSort(array) {
const { length } = array;
for (let i = 0; i < length - 1; i++) {
let indexMin = i;
// 这里与冒泡不同的是外循环的i<len-1, 以及 j = i, 必须定住最小的元素
for (let j = i; j < length; j++) {
if (array[indexMin] > array[j]) {
indexMin = j;
}
}
if (i !== indexMin) {
[array[i], array[indexMin]] = [array[indexMin], array[i]];
console.log(array);
}
}
return array;
}
let array = createNonSortedArray(7);
array = selectionSort(array);
console.log(array);
- 插入排序
function createNonSortedArray(size) {
const array = [];
for (let i = size; i > 0; i–) {
array.push(i);
}
return array;
}
function insertionSort(array) {
const { length } = array;
for (let i = 1; i < length; i++) {
// 保存待插入的值