functioninsertSort(arr) { for (let i = 1, len = arr.length; i < len; i++) { if (arr[i] < arr[i - 1]) { let current = i - 1// the position need to move let temp = arr[i] // the value need to insert arr[i] = arr[current] while (temp < arr[current]) { arr[current + 1] = arr[current] // move backward current-- } arr[current + 1] = temp } } } let arr = [6, 7, 2, 3, 1, 5, 4] insertSort(arr) console.log(arr)
functionminIndex(arr, start) { // find the mini index let min = start for (let i = start + 1, len = arr.length; i < len; i++) { if (arr[min] > arr[i]) min = i } return min } functionselectSort(arr) { let key = 0 for (let i = 0, len = arr.length; i < len; i++) { key = minIndex(arr, i) if (key != i) { // if the mini index is not the current index then exchange value ;[arr[key], arr[i]] = [arr[i], arr[key]] } } } let arr = [6, 7, 2, 3, 1, 4, 5] selectSort(arr) console.log(arr)
functionpartition(arr, low, high) { let key = arr[low] while (low < high) { // from right to left to find a value that lower than key while (low < high && arr[high] >= key) high-- ;[arr[low], arr[high]] = [arr[high], arr[low]] // from left to right to find a value thar large than key while (low < high && arr[low] <= key) low++ ;[arr[low], arr[high]] = [arr[high], arr[low]] } return low } functionquickSortFunc(arr, low, high) { if (low < high) { // binary iterations let local = partition(arr, low, high) quickSortFunc(arr, low, local - 1) quickSortFunc(arr, local + 1, high) } } functionquickSort(arr) { quickSortFunc(arr, 0, arr.length - 1) } let arr = [6, 7, 2, 3, 1, 4, 5] quickSort(arr) console.log(arr)