-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
61 lines (51 loc) · 1.57 KB
/
Copy pathQuickSort.java
File metadata and controls
61 lines (51 loc) · 1.57 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
60
61
package sorting;
public class QuickSort {
public static void main(String[] args) {
// int[] a = {8,5,4,7,31,60};
// int[] a = {7,6,5,4,3,2,1};
//int[] a = {1, 2, 3, 4, 5, 6, 7};
//int[] a = { 10, 7, 8, 9, 1, 5 };
int a[] = { 4, 3, 5, 2, 1, 3, 2, 3 };
int low = 0;
int high = a.length-1;
quickSort(a, low, high);
displayArrayData(a);
}
private static void quickSort(int[] a, int low, int high){
if(low < high) {
int pivotIndex = partition(a, low, high);
quickSort(a, low, pivotIndex-1);
quickSort(a, pivotIndex + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
// displayArrayData(arr);
int pivot = arr[high];
// Index of smaller element and indicates
// the right position of pivot found so far
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
// If current element is smaller than the pivot
if (arr[j] < pivot) {
// Increment index of smaller element
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
// displayArrayData(arr);
return (i + 1);
}
private static void displayArrayData(int[] arr) {
for(int a : arr){
System.out.print(a+", ");
}
System.out.println();
}
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}