forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.java
44 lines (38 loc) · 1.15 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
import java.util.Arrays;
public class QuickSort {
private static void quickSort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
}
private static void quickSort(int[] nums, int low, int high) {
if (low >= high) {
return;
}
int[] p = partition(nums, low, high);
quickSort(nums, low, p[0] - 1);
quickSort(nums, p[0] + 1, high);
}
private static int[] partition(int[] nums, int low, int high) {
int less = low - 1, more = high;
while (low < more) {
if (nums[low] < nums[high]) {
swap(nums, ++less, low++);
} else if (nums[low] > nums[high]) {
swap(nums, --more, low);
} else {
++low;
}
}
swap(nums, more, high);
return new int[] {less + 1, more};
}
private static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void main(String[] args) {
int[] nums = {1, 2, 7, 4, 5, 3};
quickSort(nums);
System.out.println(Arrays.toString(nums));
}
}