Skip to content

Commit 147e2cf

Browse files
authored
Create Quick Sort
1 parent baba831 commit 147e2cf

File tree

1 file changed

+93
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 5 - Recursion II

1 file changed

+93
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*
2+
Sort an array A using Quick Sort. Change in the input array itself. So no need to return or print anything.
3+
4+
Input format :
5+
Line 1 : Integer n i.e. Array size
6+
Line 2 : Array elements (separated by space)
7+
8+
Output format :
9+
Array elements in increasing order (separated by space)
10+
11+
Constraints :
12+
1 <= n <= 10^3
13+
14+
Sample Input 1 :
15+
6
16+
2 6 8 5 4 3
17+
Sample Output 1 :
18+
2 3 4 5 6 8
19+
20+
Sample Input 2 :
21+
5
22+
1 5 2 7 3
23+
Sample Output 2 :
24+
1 2 3 5 7
25+
*/
26+
27+
28+
public class Solution {
29+
30+
public static void quickSort(int[] input) {
31+
/* Your class should be named Solution
32+
* Don't write main().
33+
* Don't read input, it is passed as function argument.
34+
* No need to print or return the output.
35+
* Taking input and printing output is handled automatically.
36+
*/
37+
38+
quickSort(input,0,input.length-1);
39+
}
40+
41+
public static void quickSort(int[] input, int si, int ei)
42+
{
43+
if (si>=ei)
44+
{
45+
return;
46+
}
47+
int pivotIndex=partition(input,si,ei);
48+
quickSort(input, si, pivotIndex-1);
49+
quickSort(input,pivotIndex+1,ei);
50+
}
51+
52+
public static int partition(int[] a, int si, int ei)
53+
{
54+
int pivotElement=a[si];
55+
int smallerEleCount=0;
56+
for(int i=si+1;i<=ei;i++)
57+
{
58+
if (a[i]<pivotElement)
59+
{
60+
smallerEleCount++;
61+
}
62+
}
63+
64+
int temp=a[si+smallerEleCount];
65+
a[si+smallerEleCount]=pivotElement;
66+
a[si]=temp;
67+
68+
int i=si;
69+
int j=ei;
70+
while(i<j)
71+
{
72+
if (a[i]<pivotElement)
73+
{
74+
i++;
75+
}
76+
else if (a[j]>=pivotElement)
77+
{
78+
j--;
79+
}
80+
else
81+
{
82+
temp=a[i];
83+
a[i]=a[j];
84+
a[j]=temp;
85+
i++;
86+
j--;
87+
}
88+
}
89+
90+
return si+smallerEleCount;
91+
}
92+
93+
}

0 commit comments

Comments
 (0)