-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick Sort Code
53 lines (50 loc) · 1.39 KB
/
Quick Sort Code
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
public class Solution {
public static void quickSort(int[] input) {
/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* No need to print or return the output.
* Taking input and printing output is handled automatically.
*/
quickSort(input,0,input.length-1);
}
public static int partition(int[]input,int si,int ei){
int pivot=input[si];
int count=0;
for(int i=si+1;i<=ei;i++){
if(input[i]<=pivot){
count++;
}
}
int pivotpos=si+count;
int temp=input[pivotpos];
input[pivotpos]=pivot;
input[si]=temp;
int i=si;
int j=ei;
while(i<pivotpos && j>pivotpos){
if(input[i]<=pivot){
i++;
}
else{
if(input[j]>pivot){
j--;
}else{
int temp1=input[i];
int temp2=input[j];
input[i]=temp2;
input[j]=temp1;
}
}
}
return pivotpos;
}
public static void quickSort(int [] input,int si,int ei){
if(si>=ei){
return;
}
int pidx=partition(input,si,ei);
quickSort(input,si,pidx-1);
quickSort(input,pidx+1,ei);
}
}