-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
sort.js
88 lines (83 loc) · 2.12 KB
/
sort.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Efficient sort implementations.
*
* Note: These sort implementations were created to compare different sorting algorithms in JavaScript.
* Don't use them if you don't know what you are doing. Native Array.sort is almost always a better choice.
*
* @module sort
*/
import * as math from './math.js'
/**
* @template T
* @param {Array<T>} arr
* @param {number} lo
* @param {number} hi
* @param {function(T,T):number} compare
*/
export const _insertionSort = (arr, lo, hi, compare) => {
for (let i = lo + 1; i <= hi; i++) {
for (let j = i; j > 0 && compare(arr[j - 1], arr[j]) > 0; j--) {
const tmp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = tmp
}
}
}
/**
* @template T
* @param {Array<T>} arr
* @param {function(T,T):number} compare
* @return {void}
*/
export const insertionSort = (arr, compare) => {
_insertionSort(arr, 0, arr.length - 1, compare)
}
/**
* @template T
* @param {Array<T>} arr
* @param {number} lo
* @param {number} hi
* @param {function(T,T):number} compare
*/
const _quickSort = (arr, lo, hi, compare) => {
if (hi - lo < 42) {
_insertionSort(arr, lo, hi, compare)
} else {
const pivot = arr[math.floor((lo + hi) / 2)]
let i = lo
let j = hi
while (true) {
while (compare(pivot, arr[i]) > 0) {
i++
}
while (compare(arr[j], pivot) > 0) {
j--
}
if (i >= j) {
break
}
// swap arr[i] with arr[j]
// and increment i and j
const arri = arr[i]
arr[i++] = arr[j]
arr[j--] = arri
}
_quickSort(arr, lo, j, compare)
_quickSort(arr, j + 1, hi, compare)
}
}
/**
* This algorithm beats Array.prototype.sort in Chrome only with arrays with 10 million entries.
* In most cases [].sort will do just fine. Make sure to performance test your use-case before you
* integrate this algorithm.
*
* Note that Chrome's sort is now a stable algorithm (Timsort). Quicksort is not stable.
*
* @template T
* @param {Array<T>} arr
* @param {function(T,T):number} compare
* @return {void}
*/
export const quicksort = (arr, compare) => {
_quickSort(arr, 0, arr.length - 1, compare)
}