-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
59 lines (50 loc) · 1.64 KB
/
QuickSort.java
File metadata and controls
59 lines (50 loc) · 1.64 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
public class QuickSort {
public static int[] initialize(int[] arr) {
quickSort(arr, 0, arr.length - 1);
return arr;
}
public static void quickSort(int[] arr, int low, int high) {
System.out.println("Quicksort called: low: " + low + " high: " + high);
if (low < high) {
int pivot = divide(arr, low, high);
quickSort(arr, 0, pivot);
quickSort(arr, pivot + 1, high);
}
}
public static int divide(int[] arr, int low, int high) {
int pivot = arr[high];
int temp;
int i = low;
int j = high - 1;
// continue as long as the left pointer (i) is lower than the right pointer (j)
while (i < j) {
// find an element >= than the pivot element
while (arr[i] < pivot) {
i++;
}
// then find an element < than the pivot element
while (arr[j] >= pivot && i < j) {
j--;
}
System.out.println("low: " + low + " high: " + high);
Main.printArray(arr);
// switch the elements
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Main.printArray(arr);
}
// switch the pivot element with the element at position i
if (arr[i] >= arr[high]) {
temp = arr[i];
arr[i] = arr[high];
arr[high] = temp;
System.out.print("Pivot switch:");
Main.printArray(arr);
} else {
System.out.println("No pivot switch:");
Main.printArray(arr);
}
return i;
}
}