-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
44 lines (37 loc) · 1.05 KB
/
QuickSort.java
File metadata and controls
44 lines (37 loc) · 1.05 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
package com.aniketh;
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[] arr, int low, int high) {
if (low >= high) {
return;
}
int s = low;
int e = high;
int m = s + (e - s) / 2;
int pivot = arr[m];
while(s <= e) {
// also a reason why if it's already sorted it will not swap
while (arr[s] < pivot) {
s++;
}
while (arr[e] > pivot) {
e--;
}
if (s <= e) {
int temp = arr[s];
arr[s] = arr[e];
arr[e] = temp;
s++;
e--;
}
}
// Now my pivot is at correct index, please solve two halves now.
sort(arr, low, e);
sort(arr, s, high);
}
}