-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
34 lines (31 loc) · 1.05 KB
/
QuickSort.java
File metadata and controls
34 lines (31 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
//Like Merge Sort, QuickSort is a Divide and Conquer algorithm.
// It picks an element as a pivot and partitions the given array around the picked pivot.
public class QuickSort implements SortingAlgorithm {
public int[] sorty(int[] input) {
quickSort(input, 0, input.length - 1);
return input;
}
private void quickSort(int[] input, int low, int high) { //recursiive
if (low < high) {
int pivotIndex = partition(input, low, high);
quickSort(input, low, pivotIndex - 1);
quickSort(input, pivotIndex + 1, high);
}
}
private int partition(int[] input, int low, int high) {
int pivot = input[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (input[j] <= pivot) {
i++;
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
int temp = input[i + 1];
input[i + 1] = input[high];
input[high] = temp;
return i + 1;
}
}