-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathQuickSort.java
More file actions
47 lines (36 loc) · 1017 Bytes
/
QuickSort.java
File metadata and controls
47 lines (36 loc) · 1017 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
41
42
43
44
45
46
47
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10,1,3,9,8};
sort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
static void sort(int[] nums, int low, int hi) {
if (low >= hi) {
return;
}
int s = low;
int e = hi;
int m = s + (e - s) / 2;
int pivot = nums[m];
while (s <= e) {
// also a reason why if its already sorted it will not swap
while (nums[s] < pivot) {
s++;
}
while (nums[e] > pivot) {
e--;
}
if (s <= e) {
int temp = nums[s];
nums[s] = nums[e];
nums[e] = temp;
s++;
e--;
}
}
// now my pivot is at correct index, please sort two halves now
sort(nums, low, e);
sort(nums, s, hi);
}
}