forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
35 lines (29 loc) · 859 Bytes
/
QuickSort.java
File metadata and controls
35 lines (29 loc) · 859 Bytes
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
public class QuickSort {
public static void sort(int[] a) {
sort(a, 0, a.length - 1);
}
public static void sort(int[] a, int low, int high) {
if (low >= high) return;
int middle = partition(a, low, high);
sort(a, low, middle - 1);
sort(a, middle + 1, high);
}
private static int partition(int[] a, int low, int high) {
int middle = low + (high - low) / 2;
swap(a, middle, high);
int storeIndex = low;
for (int i = low; i < high; i++) {
if (a[i] < a[high]) {
swap(a, storeIndex, i);
storeIndex++;
}
}
swap(a, high, storeIndex);
return storeIndex;
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}