-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathQuickSort.java
More file actions
73 lines (66 loc) · 1.88 KB
/
QuickSort.java
File metadata and controls
73 lines (66 loc) · 1.88 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
62
63
64
65
66
67
68
69
70
71
72
73
package com.examplehub.sorts;
public class QuickSort implements Sort {
@Override
public void sort(int[] numbers) {
quickSort(numbers, 0, numbers.length - 1);
}
private int partition(int[] number, int left, int right) {
int pivot = number[left];
while (left != right) {
while (left != right && number[right] >= pivot) {
right--;
}
number[left] = number[right];
while (left != right && number[left] <= pivot) {
left++;
}
number[right] = number[left];
}
number[left] = pivot;
return left;
}
/**
* QuickSort algorithm implements.
*
* @param numbers the numbers to be sorted.
*/
public void quickSort(int[] numbers, int left, int right) {
if (left < right) {
int pivotIndex = partition(numbers, left, right);
quickSort(numbers, left, pivotIndex - 1);
quickSort(numbers, pivotIndex + 1, right);
}
}
/**
* Generic quickSort algorithm implements.
*
* @param array the array to be sorted.
* @param <T> the class of the objects in the array.
*/
@Override
public <T extends Comparable<T>> void sort(T[] array) {
quickSort(array, 0, array.length - 1);
}
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) {
T pivot = array[left];
while (left != right) {
while (left != right && array[right].compareTo(pivot) >= 0) {
right--;
}
array[left] = array[right];
while (left != right && array[left].compareTo(pivot) <= 0) {
left++;
}
array[right] = array[left];
}
array[left] = pivot;
return left;
}
public static <T extends Comparable<T>> void quickSort(T[] array, int left, int right) {
if (left < right) {
int pivotIndex = partition(array, left, right);
quickSort(array, left, pivotIndex - 1);
quickSort(array, pivotIndex + 1, right);
}
}
}