-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathquicksort.js
More file actions
44 lines (38 loc) · 859 Bytes
/
quicksort.js
File metadata and controls
44 lines (38 loc) · 859 Bytes
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
type int = number
type ints = int[]
function swap(array: ints, i: int, j: int) {
let ai = array[i]
array[i] = array[j]
array[j] = ai
}
function partition(values: ints, l: int, r: int): int {
let x = values[r]
let less = l
let i = l
while (i < r) {
let value = values[i]
if (value <= x) {
swap(values, i, less)
less = less + 1
}
i = i + 1
}
swap(values, less, r)
return less
}
function quickSortImpl(values: ints, l: int, r: int) {
if (l < r) {
let q = partition(values, l, r)
quickSortImpl(values, l, q - 1)
quickSortImpl(values, q + 1, r)
}
}
function quickSort(values: ints) {
let n = ~values
if (n != 0) {
quickSortImpl(values, 0, n - 1)
}
}
let numbers = [6,2,4,3,7,1,5,]
quickSort(numbers)
>>>numbers