-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathQuickSort.java
60 lines (55 loc) · 1.29 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package chapter10SortingAndSearching;
import java.util.Arrays;
/**
*
* Problem:Quick Sort, not stable
*
* Time Complexity: O(NlogN) for average, O(N^2) for worst case.
*
* Space Complexity: O(logN)
*
*/
public class QuickSort {
public int[] quickSort(int[] nums, int left, int right) {
int index = partition(nums, left, right);
if (left < index - 1) {
// sort left
quickSort(nums, left, index - 1);
}
if (index < right) {
// sort right
quickSort(nums, index, right);
}
return nums;
}
private int partition(int[] nums, int left, int right) {
int pivot = nums[(left + right) / 2];
while (left <= right) {
// find element on left that should be on right
while (nums[left] < pivot) {
left++;
}
// find element on right that should be on left
while (nums[right] > pivot) {
right--;
}
// swap elements, and move left and right indices
if (left <= right) {
swap(nums, left, right);
left++;
right--;
}
}
return left;
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static void main(String[] args) {
QuickSort q = new QuickSort();
int[] nums = { 3, 2, 1, 12, 4, 5, 3 };
System.out.println(Arrays.toString(q.quickSort(nums, 0, nums.length - 1)));
}
}