-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
42 lines (35 loc) · 1.09 KB
/
Copy pathQuickSort.java
File metadata and controls
42 lines (35 loc) · 1.09 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
import java.util.Arrays;
public class QuickSort {
public static int findPivot(int[] arr, int lo, int hi) {
int pivot = arr[hi];
int boundary = lo - 1;
for (int i = lo; i < hi; i++) {
if (arr[i] <= pivot) {
boundary++;
swap(arr, boundary, i);
}
}
++boundary;
swap(arr, hi, boundary);
return boundary;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void quickSort(int[] arr, int lo, int hi){
if (lo < hi) {
int pivot = findPivot(arr, lo, hi);
quickSort(arr, lo, pivot - 1);
quickSort(arr, pivot+1, hi);
}
}
public static void main(String[] args) {
int[] arr = new int[] { -1, 1, 3, 2, 4, 0, 1 };
// System.out.println(findPivot(arr, 0, arr.length - 1));
// System.out.println(Arrays.toString(arr));
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
}