排序算法
现有数组[7, 5, 4, 15, 3, 9, 6, 12]
,进行升序排序:
冒泡排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Array.prototype.bubbleSort = function () { for (let i = 0; i < this.length - 1; i++) { for (let j = 0; j < this.length - 1 - i; j++) { if (this[j] > this[j + 1]) { let temp = this[j]; this[j] = this[j + 1]; this[j + 1] = temp; } } } };
const arr = [7, 5, 4, 15, 3, 9, 6, 12]; arr.bubbleSort(); console.log(arr);
|
选择排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| Array.prototype.selectionSort = function () { for (let i = 0; i < this.length - 1; i++) { let indexMin = i; for (let j = i; j < this.length; j++) { if (this[j] < this[indexMin]) { indexMin = j; } } if (indexMin !== i) { let temp = this[i]; this[i] = this[indexMin]; this[indexMin] = temp; } } };
const arr = [7, 5, 4, 15, 3, 9, 6, 12]; arr.selectionSort(); console.log(arr);
|
插入排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| Array.prototype.insertionSort = function () { for (let i = 1; i < this.length; i++) { const temp = this[i]; let j = i; while (j > 0) { if (this[j - 1] > temp) { this[j] = this[j - 1]; } else { break; } j--; } this[j] = temp; } };
const arr = [7, 5, 4, 15, 3, 9, 6, 12]; arr.insertionSort(); console.log(arr);
|
归并排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| Array.prototype.mergeSort = function () { const rec = arr => { if (arr.length === 1) return arr; const mid = Math.floor(arr.length / 2); const left = arr.slice(0, mid); const right = arr.slice(mid, arr.length); const orderLeft = rec(left); const orderRight = rec(right); const res = []; while (orderLeft.length || orderRight.length) { if (orderLeft.length && orderRight.length) { res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift()); } else if (orderLeft.length) { res.push(orderLeft.shift()); } else if (orderRight.length) { res.push(orderRight.shift()); } } return res; }; const res = rec(this); res.forEach((item, index) => { this[index] = item; }); };
const arr = [7, 5, 15, 4, 9, 3, 12, 6]; arr.mergeSort(); console.log(arr);
|
快速排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| Array.prototype.quickSort = function () { const rec = arr => { if (arr.length <= 1) { return arr; } const left = []; const right = []; const mid = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] < mid) { left.push(arr[i]); } else { right.push(arr[i]); } } return [...rec(left), mid, ...rec(right)]; }; const res = rec(this); res.forEach((item, index) => { this[index] = item; }); };
const arr = [7, 5, 4, 15, 3, 9, 6, 12]; arr.quickSort(); console.log(arr);
|