forked from Anurag2622002/Codefornewccoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuicksort.java
45 lines (38 loc) · 1.04 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
import java.io.*;
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));
Arrays.sort(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);
}
}