-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQuickSort.java
More file actions
62 lines (49 loc) · 940 Bytes
/
QuickSort.java
File metadata and controls
62 lines (49 loc) · 940 Bytes
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
package sorting;
/**
* Quick sort for Integer arrays
*
* @time complexity O(n log n) in the average case and O(n^2) in the worst case
* @space complexity O(log n)
*/
public class QuickSort {
public void sort(int[] elements, int left, int right) {
int i = left, j = right;
int pivot = elements[(left + right) / 2];
while (i <= j) {
while (elements[i] < pivot) {
i++;
}
while (elements[j] > pivot) {
j--;
}
if (i <= j) {
// Swap
int tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
// Recursive calls
if (left < j) {
sort(elements, left, j);
}
if (i < right) {
sort(elements, i, right);
}
}
public String display(int[] arr) {
String out = "[ ";
int i = 0;
while (i < arr.length) {
if (i != arr.length - 1) {
out += arr[i] + ", ";
} else {
out += arr[i] + "]";
}
i++;
}
return out;
}
}