-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
46 lines (37 loc) · 1 KB
/
Copy pathQuickSort.java
File metadata and controls
46 lines (37 loc) · 1 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
43
44
45
46
package Recursion;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr= {5, 4, 3, 2, 1};
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 it 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);
}
}