-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
59 lines (46 loc) · 1.62 KB
/
QuickSort.java
File metadata and controls
59 lines (46 loc) · 1.62 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
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] input = { 2, 5, 6, 7, 1, 8 };
System.out.print(Arrays.toString(input));
quickSort(0, input.length - 1, input);
System.out.print(Arrays.toString(input));
}
private static void quickSort(int low, int high, int[] array) {
if (low < high) {
int j = partition(low, high, array);
quickSort(low, j, array);
quickSort(j + 1, high, array);
}
}
private static int partition(int low, int high, int[] array) {
int pivot = array[low];
int i = low, j = high;
while (i < j) {// until unsorted
// increment until the found value is lesser than pivot.
// or increment until you find value greater than the pivot.
do {
i++;
System.out.print("i" + i + " ");
} while (array[i] <= pivot);
// decrement until the found value is greater than pivot.
// or decrement until you find value lesser than the pivot.
do {
j--;
System.out.print("j" + j + " ");
} while (array[j] > pivot);
// exchange the values as they belong to other part of partition.
if (i < j) {
swap(i, j, array);
}
}
System.out.println("won"+ j);
swap(j, low, array);
return j;
}
private static void swap(int i, int j, int[] array) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}