-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
40 lines (35 loc) · 828 Bytes
/
QuickSort.java
File metadata and controls
40 lines (35 loc) · 828 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
36
37
38
39
40
public class QuickSort {
public static void main(String[] args) {
int[] x = {2, 8, 7, 1, 3, 5, 6, 4};
sort(x);
for (int i : x) {
System.out.print(i + " ");
}
}
public static void sort(int[] x) {
quickSort(x, 0, x.length-1);
}
private static void quickSort(int[] x, int start, int end) {
if (start < end) {
int pivot = partition(x, start, end);
quickSort(x, start, pivot-1);
quickSort(x, pivot+1, end);
}
}
private static int partition(int[] x, int start, int end) {
int pivot = x[end];
int i = start -1;
for (int j = start; j <= end-1; j++) {
if (x[j] <= pivot) {
i++;
int tmp = x[j];
x[j] = x[i];
x[i] = tmp;
}
}
int tmp = x[i+1];
x[i+1] = x[end];
x[end] = tmp;
return i+1;
}
}