-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathThreeWayQuickSort.java
More file actions
57 lines (46 loc) · 1.24 KB
/
Copy pathThreeWayQuickSort.java
File metadata and controls
57 lines (46 loc) · 1.24 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
public class ThreeWayQuickSort {
public static void main(String a[]) {
int[] arr1 = { 9, 14, 3, 2, 43, 11, 58, 22 };
System.out.println("Before Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();
sort(arr1, 0, arr1.length - 1);// sorting array using insertion sort
System.out.println("After Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
}
public static void sort(int[] array, int leftIndex, int rightIndex) {
if (array.length > 1 && leftIndex < rightIndex) {
int[] resposta = partition(array, leftIndex, rightIndex);
sort(array, leftIndex, resposta[0] - 1);
sort(array, resposta[1] + 1, rightIndex);
}
}
private static int[] partition(int[] array, int leftIndex, int rightIndex) {
int j = leftIndex;
int k = rightIndex;
int nPivot = array[leftIndex];
int i = leftIndex;
while (i <= k) {
if (array[i] == (nPivot))
++i;
else if (array[i] > (nPivot))
swap(array, i, k--);
else {
swap(array, i++, j++);
}
}
int[] resposta = { j, k };
return resposta;
}
public static void swap(int[] array, int i, int j) {
if (array == null)
throw new IllegalArgumentException();
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}