forked from joeyajames/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.java
61 lines (44 loc) · 1.3 KB
/
QuickSort.java
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
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
public void quickSort(int[] A) {
quickSort(A, 0, A.length-1);
}
private void quickSort(int[] A, int low, int high) {
if (low < high+1) {
int p = partition(A, low, high);
quickSort(A, low, p-1);
quickSort(A, p+1, high);
}
}
private void swap(int[] A, int index1, int index2) {
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
// returns random pivot index between low and high inclusive.
private int getPivot(int low, int high) {
Random rand = new Random();
return rand.nextInt((high - low) + 1) + low;
}
// moves all n < pivot to left of pivot and all n > pivot
// to right of pivot, then returns pivot index.
private int partition(int[] A, int low, int high) {
swap(A, low, getPivot(low, high));
int border = low + 1;
for (int i = border; i <= high; i++) {
if (A[i] < A[low]) {
swap(A, i, border++);
}
}
swap(A, low, border-1);
return border-1;
}
public static void main(String[] args) {
QuickSort qs = new QuickSort();
int[] A = {9, 0, 1, 3, 4, 5, 2, 9, 8, 7, 6, 5, 9, 1, 0, 9};
System.out.println(Arrays.toString(A));
qs.quickSort(A);
System.out.println(Arrays.toString(A));
}
}