冒泡排序
- 原地排序
- 稳定排序
时间复杂度:O(n^2)
function dubbleSort (arr) {for(let i = 0; i < arr.length; i++) {let flag = false;for(let j = 0; j < arr.length - i - 1; j++) {if (arr[j] > arr[j+1]) {const temp = arr[j+1];arr[j+1] = arr[j];arr[j] = temp;flag = true;}}if (!flag) break;}return arr;}
选择排序
原定排序
- 不稳定排序
时间复杂度:O(n^2)
function selectionSort (arr) {let minIndex = 0;for(let i = 0; i < arr.length; i++) {minIndex = i;for(let j = i + 1; j < arr.length; j++) {if (arr[j] < arr[minIndex]) {minIndex = j;}}const temp = arr[minIndex];arr[minIndex] = arr[i];arr[i] = temp;}return arr;}
插入排序
原地排序
- 稳定排序
时间复杂度:O(n^2)
function insertionSort (arr) {for(let i = 1; i < arr.length; i++) {let value = a[i];let j = i - 1;for(; j >= 0; j--) {if (a[j] > value) {a[j+1] = a[j];}}a[j+1] = value;}}
归并排序
非原地排序
- 稳定排序
- 时间复杂度:O(nlog(n)) ```javascript const mergeSort = function(arr) { if (arr.length < 2) return arr; const midIndex = Math.floor(arr.length / 2); const left = arr.slice(0, midIndex); const right = arr.slice(midIndex, arr.length); return merge(mergeSort(left), mergeSort(right)); }
const merge = function(left, right) { const res = []; while(left.length && right.length) { if (left[0] <= right[0]) { res.push(left.shift()); } else { res.push(right.shift()); } } while(left.length) res.push(left.shift()); while(right.length) res.push(right.shift()); return res }
<a name="yGrXN"></a>## 快速排序- 原地排序- 非稳定排序- 时间复杂度:O(nlog(n))```javascriptconst quickSort = function(arr) {if (arr.length < 2) return arr;const midIndex = Math.floor(arr.length / 2);const mid = arr.splice(midIndex, 1)[0];const left = [];const right = [];for(let i = 0; i < arr.length; i++) {if (arr[i] < mid) {left.push(arr[i]);} else {right.push(arr[i]);}}return quickSort(left).concat([mid], quickSort(right));}
