-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path![T]QuickSort.java
More file actions
34 lines (31 loc) · 956 Bytes
/
![T]QuickSort.java
File metadata and controls
34 lines (31 loc) · 956 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
//sort by pivot
/*The difference between quick sort and quick select is in quickSort function.
As quick select only proceed with one of two halves. So need if else to determine which half to proceed;
*/
// right boundary should be the idx of last element(arr.length - 1);
private void quickSort(int[] arr, int l, int r){
if(l < r){
int mid = partition(arr,left, end);
quickSort(l, mid - 1);
quickSort(mid + 1, l);
// for quick select
if(target == arr[mid]){
return mid;
}else if(target < mid){
return quickSort(l, mid - 1)
}else{
return quickSort(mid + 1, r)
}
}
}
private void partition(int[] arr, int l, int r){
int pivot = arr[l];
while(l < r){
while(l < r && arr[r] >= pivot) --r;
arr[l] = arr[r];
while(l < r && arr[l] <= pivot) ++l;
arr[r] = arr[l]
}
arr[l] = pivot;
return l;
}