forked from JCarlosR/Sorting-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeWayQuickSort.java
More file actions
77 lines (57 loc) · 1.88 KB
/
ThreeWayQuickSort.java
File metadata and controls
77 lines (57 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
74
75
76
77
/** autor: Edimar Chaves Jr.
* 02/10/2019 13:40:33
*
* @param <T> T is a generic comparable type (Integer for exemple)
*
* The Three way quicksort it is an optimized version of traditional quicksort
* this one deals better with several occurrences of elements equal to the pivot.
**/
public class ThreeWayQuickSort<T extends Comparable<T>> {
/** The main method.
*
* @param array a generic collection to be sorted.
* @param left the begin of the order.
* @param right the end of the order.
**/
public void sort(T[] array, int left, int right) {
if (left < right) this.partition(array, left, right);
}
/** The partition of array method.
*
* @param array a generic collection to partition.
* @param left the begin of partition.
* @param right the end of partition.
*/
private void partition(T[] array, int left, int right) {
if (left < right) {
int start = left;
int end = right;
int i = left;
T pivot = array[left];
while (i <= end) {
if (array[i].compareTo(pivot) < 0) {
this.swap(array, start, i);
start++;
i++;
} else if (array[i].compareTo(pivot) > 0) {
this.swap(array, i, end);
end--;
} else i++;
}
sort(array, left, start - 1);
sort(array, end + 1, right);
}
}
/**
* The swap method.
*
* @param array a generic collection.
* @param i the index of the element that will be swapped with the j-element.
* @param j the index of the element that will be swapped with de i-element.
*/
private void swap(T[] array, int i, int j){
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}