-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.java
More file actions
79 lines (63 loc) · 2.14 KB
/
Copy pathSort.java
File metadata and controls
79 lines (63 loc) · 2.14 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
78
79
package IntensiveCourse.Lesson1;
import java.util.Comparator;
public class Sort {
/**
* Recursively sorts a given list with a middle elements as
* the Pivot from and to a given index.
*
* @param array - array to sort
* @param fromIndex - first index of which to sort
* @param toIndex - last index of which to sort
*/
public static <E> void quicksort(E[] array, int fromIndex, int toIndex) {
if (fromIndex >= toIndex)
return;
int left = fromIndex, right = toIndex;
E pivot = array[(fromIndex + toIndex) / 2];
while (left <= right) {
while (((Comparable) array[left]).compareTo(pivot) < 0)
left++;
while (((Comparable) array[right]).compareTo(pivot) > 0)
right--;
if (left > right)
break;
swap(left, right, array);
left++;
right--;
}
quicksort(array, fromIndex, right);
quicksort(array, left, toIndex);
}
/**
* Recursively sorts given list by a given comparator with a middle
* elements as the Pivot from and to a given index.
*
* @param array - array to sort
* @param fromIndex - first index of which to sort
* @param toIndex - last index of which to sort
*/
public static <E> void quicksort(E[] array, int fromIndex, int toIndex, Comparator<? super E> c) {
if (fromIndex >= toIndex)
return;
int left = fromIndex, right = toIndex;
E pivot = array[(fromIndex + toIndex) / 2];
while (left <= right) {
while (c.compare(array[left], pivot) < 0)
left++;
while (c.compare(array[right], pivot) > 0)
right--;
if (left > right)
break;
swap(left, right, array);
left++;
right--;
}
quicksort(array, fromIndex, right);
quicksort(array, left, toIndex);
}
private static <E> void swap(int i, int j, E[] array) {
E temp = (E) array[i];
array[i] = array[j];
array[j] = temp;
}
}