-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick sort
More file actions
84 lines (71 loc) · 1.92 KB
/
quick sort
File metadata and controls
84 lines (71 loc) · 1.92 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
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {5,4,3,2,1};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
private static void quickSort(int[] arr, int low, int high) {
if(low>=high)return;
int start=low;
int end=high;
int mid=start+(end-start)/2;
int pivot=arr[mid];
while(start<=end){
while(arr[start]<pivot){
start++;
}
while(arr[end]>pivot){
end--;
}
if(start<=end){
swap(arr,start,end);
start++;
end--;
}
}
quickSort(arr,low,end);
quickSort(arr,start,high);
}
private static void dualPivotQuickSort(int[] arr,int low,int high){
if(low>=high) return;
if(arr[low]>arr[high]){
swap(arr,low,high);
}
int pivot1=arr[low];
int pivot2=arr[high];
int index=low+1;
int start=low+1;
int end=high-1;
while(index<=end){
if(arr[index]<pivot1){
swap(arr,index,start);
start++;
}else if(arr[index]>pivot2){
swap(arr,index,end);
end--;
index--;
}
index++;
}
start--;
end++;
swap(arr,low,start);
swap(arr,high,end);
//for left of pivot1
dualPivotQuickSort(arr,low,start-1);
//for between the pivots
if(arr[start]!=arr[end]){
dualPivotQuickSort(arr,start,end-1);
}
//for right of pivot2
dualPivotQuickSort(arr,end+1,high);
}
private static void swap(int[] arr,int i,int j){
if(i!=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}