Repository navigation
Expand file tree
/
Copy pathQuickSort.java
More file actions
75 lines (59 loc) · 2.35 KB
/
Copy pathQuickSort.java
File metadata and controls
75 lines (59 loc) · 2.35 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
package algorithms;
public class QuickSort {
public int[] sort(int[] array) {
// Pick a pivot element randomly
// Walk through the array making sure that all the elements
// are smaller before the pivot, and that all elements after are bigger
// and we do this in place! That's the killer feature. No extra array required.
//
// Then we repeat the process to the left and right portions over and over again
// Then eventually our array becomes sorted.
quickSort(array, 0, array.length - 1);
return array;
}
private void quickSort(int[] array, int left, int right) {
if (left >= right) {
return;
}
// Step 1: Pick a pivot element - we will choose the center
// Better would be to choose left + (right-left)/2 (as this would avoid overflow error for large arrays i.e. 2GB))
int pivot = array[(left + right)/2];
// Step 2: Partition the array around this pivot - return the index of the partition
int index = partition(array, left, right, pivot);
// Step 3: Sort on the left and the right side
quickSort(array, left, index - 1);
quickSort(array, index, right);
}
private int partition(int[] array, int left, int right, int pivot) {
// Move the left and right pointers in towards each other
while (left <= right) {
// Move left until you find an element bigger than the pivot
while(array[left] < pivot) {
left++;
}
// Move right until you find an element smaller than the pivot
while (array[right] > pivot) {
right--;
}
// Then swap
if (left <= right) {
swap(array, left, right);
left++;
right--;
}
}
// When we get here, everything in this partition will be in the right order
// Now we need to return next partition point - which for us will be left
return left;
}
private void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
public void prettyPrint(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}