-
Notifications
You must be signed in to change notification settings - Fork 13
/
quickSort.js
118 lines (97 loc) · 2.27 KB
/
quickSort.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<script>
// javascript program for 3-way quick sort
var i, j;
/*
* This function partitions a in three parts a) a[l..i] contains all elements
* smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c)
* a[j..r] contains all elements greater than pivot
*/
function partition(a , l , r) {
i = l - 1;
j = r;
var p = l - 1, q = r;
var v = a[r];
while (true) {
// From left, find the first element greater than
// or equal to v. This loop will definitely
// terminate as v is last element
while (a[++i] < v)
;
// From right, find the first element smaller than
// or equal to v
while (v < a[--j])
if (j == l)
break;
// If i and j cross, then we are done
if (i >= j)
break;
// Swap, so that smaller goes on left greater goes
// on right
var temp = a[i];
a[i] = a[j];
a[j] = temp;
// Move all same left occurrence of pivot to
// beginning of array and keep count using p
if (a[i] == v) {
p++;
temp = a[i];
a[i] = a[p];
a[p] = temp;
}
// Move all same right occurrence of pivot to end of
// array and keep count using q
if (a[j] == v) {
q--;
temp = a[q];
a[q] = a[j];
a[j] = temp;
}
}
// Move pivot element to its correct index
var temp = a[i];
a[i] = a[r];
a[r] = temp;
// Move all left same occurrences from beginning
// to adjacent to arr[i]
j = i - 1;
for (k = l; k < p; k++, j--) {
temp = a[k];
a[k] = a[j];
a[j] = temp;
}
// Move all right same occurrences from end
// to adjacent to arr[i]
i = i + 1;
for (k = r - 1; k > q; k--, i++) {
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
// 3-way partition based quick sort
function quicksort(a , l , r) {
if (r <= l)
return;
i = 0;
j = 0;
// Note that i and j are passed as reference
partition(a, l, r);
// Recur
quicksort(a, l, j);
quicksort(a, i, r);
}
// A utility function to print an array
function printarr(a , n) {
for (i = 0; i < n; ++i)
document.write(" "+ a[i]);
document.write("<br/>");
}
// Driver code
var a = [ 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 ];
var size = a.length;
// Function Call
printarr(a, size);
quicksort(a, 0, size - 1);
printarr(a, size);
// This code contributed by aashish1995
</script>