-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
79 lines (67 loc) · 2.01 KB
/
QuickSort.java
File metadata and controls
79 lines (67 loc) · 2.01 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 kb.sort;
import kb.sort.api.Sortable;
public class QuickSort implements Sortable {
/*
* Quick Sort.
* n.log(n) time for average and base case, O(n^2) for the worst case.
* O(1) space
* Stable: No
*/
@Override
public int[] sort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int lo, int hi) {
if (lo >= hi)
return;
int pivIndex = partition(nums, lo, hi);
quickSort(nums, lo, pivIndex - 1);
quickSort(nums, pivIndex + 1, hi);
}
/**
* Partitions the input without an auxiliary array.
*/
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1; // index of smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than the pivot
if (arr[j] < pivot) {
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
/**
* Uses additional memory for the auxiliary array.
*/
@SuppressWarnings("unused")
private int partitionVariant(int[] nums, int lo, int hi) {
int[] tmp = new int[hi - lo + 1];
int tail = tmp.length - 1;
int head = 0;
int piv = nums[lo];
for (int i = lo + 1; i <= hi; i++)
if (nums[i] < piv)
tmp[head++] = nums[i];
else
tmp[tail--] = nums[i];
tmp[head] = piv;
// copy back the auxiliary array to the original
for (int i = 0; i < tmp.length; i++)
nums[lo + i] = tmp[i];
return head + lo;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}