-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
121 lines (110 loc) · 2.28 KB
/
QuickSort.java
File metadata and controls
121 lines (110 loc) · 2.28 KB
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
119
120
121
package sorting;
/**
* Sort a given array using Quick sort.
*
* Link: http://geeksquiz.com/quick-sort/
*
* @author shivam.maharshi
*/
public class QuickSort {
public static int[] sort(int[] a) {
sort(a, 0, a.length - 1);
return a;
}
private static void sort(int[] a, int l, int h) {
if (l < h) {
int p = lowPar(a, l, h);
p = highPar(a, l, h);
p = midPar(a, l, h);
p = randPar(a, l, h);
sort(a, l, p - 1);
sort(a, p + 1, h);
}
}
// This is partitioning around the median element as pivot.
// This has fixed O(nLog(n)) worst case complexity.
@SuppressWarnings("unused")
private static int medPar(int[] a, int l, int h) {
// TODO:
return 0;
}
// This is partitioning around a random element as pivot.
private static int randPar(int[] a, int l, int h) {
int pivot = ((int) ((h - l) * Math.random())) + l;
int val = a[pivot];
int i = l;
int j = h;
while (i < j) {
if (a[i] < val) {
i++;
} else if (a[j] > val) {
j--;
} else {
swap(a, i, j);
i++;
j--;
}
}
return i;
}
// This is partitioning around mid element as pivot.
private static int midPar(int[] a, int l, int h) {
int pivot = (l + h) / 2;
int val = a[pivot];
int i = l;
int j = h;
while (i < j) {
if (a[i] < val) {
i++;
} else if (a[j] > val) {
j--;
} else {
swap(a, i, j);
i++;
j--;
}
}
return i;
}
// This is partitioning around the last element as pivot.
private static int highPar(int[] a, int l, int h) {
int pivot = h;
int i = l;
int j = l;
while (j < h) {
if (a[j] < a[pivot]) {
swap(a, i, j);
i++;
}
j++;
}
swap(a, i, j);
return i;
}
// This is partitioning around the first element as pivot.
private static int lowPar(int[] a, int l, int h) {
int pivot = l;
int i = l;
int j = l + 1;
while (j <= h) {
if (a[pivot] > a[j]) {
i++;
swap(a, i, j);
}
j++;
}
swap(a, pivot, i);
return i;
}
private static void swap(int[] a, int i, int j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
public static void main(String[] args) {
int[] a = { 3, 1, 4, 1, 5, 9, 2 };
sort(a);
for (int aa : a)
System.out.print(aa + " ");
}
}