-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
116 lines (107 loc) · 3.14 KB
/
QuickSort.java
File metadata and controls
116 lines (107 loc) · 3.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.util.ArrayList;
public class SortLevel {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static int factorial(int n, int a) {
if (n < 0) {
return 0;
}
if (n == 0) {
return 1;
}
if (n == 1) {
return a;
}
return factorial(n - 1, n * a);
}
public static void print(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
public static void QuickSortTailOptimization(int[] array, int left, int right) {
while (left < right) {
int pivot = ArrayChunk(array, left, right);
QuickSortTailOptimization(array, left, pivot - 1);
left = pivot + 1;
}
}
public static void QuickSort(int[] array, int left, int right) {
while (left < right) {
int pivot = ArrayChunk(array, left, right);
if (pivot - left < right - pivot) {
QuickSort(array, left, pivot - 1);
left = pivot + 1;
} else {
QuickSort(array, pivot + 1, right);
right = pivot - 1;
}
}
}
public static int ArrayChunk(int[] array, int left, int right) {
int i = left;
int j = right;
int index = (left + right) / 2;
int frame = array[index];
int temp;
boolean goTo = false;
while (true) {
if (goTo) {
i = left;
j = right;
index = (left + right) / 2;
frame = array[index];
goTo = false;
}
while (array[i] < frame) {
i++;
}
while (array[j] > frame) {
j--;
}
if ((i == (j - 1)) && (array[i] > array[j])) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
if (array[i] == frame) {
index = i;
} else if (array[j] == frame) {
index = j;
}
goTo = true;
} else if ((i == j) || ((array[i] < array[j]) && i == j - 1)) {
return index;
} else {
temp = array[i];
array[i] = array[j];
array[j] = temp;
if (array[i] == frame) {
index = i;
} else if (array[j] == frame) {
index = j;
}
}
}
}
public static ArrayList<Integer> KthOrderStatisticsStep(int[] Array, int L, int R, int k) {
ArrayList<Integer> list = new ArrayList<>();
int pivot = ArrayChunk(Array, L, R);
if (pivot == k) {
list.add(L);
list.add(R);
return list;
} else if (pivot > k) {
R = pivot - 1;
} else {
L = pivot + 1;
}
list.add(L);
list.add(R);
return list;
}
}