functionSelectionSort(arr) { var len = arr.length; for (var i = 0; i < len; i++) { var min = arr[i]; var index = i; for (var j = i + 1; j < len; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } if (index != i) { var temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } } return arr; }
// es6 functionSelectionSort(arr) { const len = arr.length; for (let i = 0 ;i < len - 1; i++) { for (let j = i ; j<len; j++) { if (arr[j] < arr[i]) { [arr[i],arr[j]] = [arr[j],arr[i]]; } } } return arr }
functionInsertionSort(arr) { var len = arr.length; for (var i = 0; i < len - 1; i++) { var insert = arr[i+1]; var index = i + 1; for (var j = i; j >= 0; j--) { if (insert < arr[j]) { arr[j+1] = arr[j]; index = j; } } arr[index] = insert; } return arr; }
// es 6 functionInserttionSort(arr) { const len = arr.length; for (let i = 0; i < len - 1; i++) { for (let j = i; j > 0; j--) { if (arr[j] < arr[j-1]) { [arr[j], arr[j-1]] = [arr[j-1], arr[j]]; } else { break; } } } }
复杂度:
平均时间复杂度
最好情况
最坏情况
空间复杂度
稳定性
O(n^2)
O(n)
O(n^2)
O(1)
稳定
四、希尔排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functionShellSort(arr) { var len = arr.length; var gap = Math.round(len / 2); while (gap > 0) { for (var i = gap; i < len; i++) { var insert = arr[i]; var index = i; for (var j = i; j >= 0; j -= gap) { if (insert < arr[j]) { arr[j + gap] = arr[j]; index = j; } } arr[index] = insert; } gap = Math.round(gap/2 - 0.1); } return arr; }
复杂度:
平均时间复杂度
最好情况
最坏情况
空间复杂度
稳定性
O(n^1.3)
O(n)
O(n^2)
O(1)
不稳定
五、归并排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
functionmerge(leftArr, rightArr) { var result = [] while (leftArr.length > 0 && rightArr.length > 0) { if (leftArr[0] < rightArr[0]) result.push(leftArr.shift()) // 把最小的最先取出,放到结果集中 else result.push(rightArr.shift()) } return result.concat(leftArr).concat(rightArr) // 剩下的就是合并,这样就排好序了 }
functionmergeSort(array) { if (array.length == 1) return array var middle = Math.floor(array.length / 2) // 求出中点 var left = array.slice(0, middle) // 分割数组 var right = array.slice(middle) return merge(mergeSort(left), mergeSort(right)) // 递归合并与排序 }
functionQuickSort(arr) { var len = arr.length; if (len <= 1) { return arr; } else { var smaller = []; var bigger = []; var base = [arr[0]]; for (var i = 1; i < len; i++) { if (arr[i] <= base[0]) { smaller.push(arr[i]); } else { bigger.push(arr[i]); } } return QuickSort(smaller).concat(base.concat(QuickSort(bigger))); } }
// es6 functionQuickSort(arr) { const len = arr.length; if (len <= 1) { return arr; } else { const smallers = []; const biggers = []; const base = arr[0]; for (let i = 1; i < len; i++) { if (arr[i] <= base) { smallers.push(arr[i]); } else { biggers.push(arr[i]); } } return [...QuickSort(smallers), base, ...QuickSort(biggers)]; } }