文章目錄
  1. 1. Quick Sort - Javascript example

Quick Sort - Javascript example

The following code sample is implemented with Lomuto partition scheme, which selects the last element as pivot.

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
function quicksort(array, start, end){
if (start < end){
var pivotIdx = partition(array, start, end);

// divide and conquer
quicksort(array, start, pivotIdx - 1);
quicksort(array, pivotIdx + 1, end);
}
}

function partition(array, start, end){
var pivot = array[end];

// idx counter for element smaller or equal to the pivot
var idx = start;

// ignore the last one becasue it is pivot
var i = start;
for (i = start; i < end; i++){
if (array[i] <= pivot){
swap(array, i, idx);
idx++;
}
}

// swap the pivot back to the center
swap(array, idx, end);

return idx;
}

function swap(array, a, b){
var temp = array[a];
array[a] = array[b];
array[b] = temp;
}

function test(array){
console.debug('Test: ' + array);
quicksort(array, 0, array.length - 1);
console.debug(' => ' + array);
}

test([1,2,3]);
test([1,3,2]);
test([3,2,1]);

test([1,2,3,4]);
test([2,1,3,4]);
test([2,3,1,4]);
test([2,3,4,1]);
test([1,3,2,4]);
test([1,3,4,2]);
test([1,2,4,3]);

文章評論

文章目錄
  1. 1. Quick Sort - Javascript example