-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick Sort
46 lines (41 loc) · 1.07 KB
/
Quick Sort
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
class Solution
{
static void swap(int[] arr, int x, int y)
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
//Function to sort an array using quick sort algorithm.
static void quickSort(int arr[], int st, int end)
{
if(st >= end) return;
int pi = partition(arr, st, end);
quickSort(arr, st, pi-1);
quickSort(arr, pi+1, end);
}
static int partition(int arr[], int st, int end)
{
int pivot = arr[st];
int cnt = 0;
for(int i = st+1; i <= end; i++)
{
if(arr[i] <= pivot) cnt++;
}
int pivotIdx = st + cnt;
swap(arr, st, pivotIdx);
int i = st, j = end;
while(i < pivotIdx && j > pivotIdx)
{
while (arr[i] <= pivot) i++;
while (arr[j] > pivot) j--;
if(i < pivotIdx && j > pivotIdx)
{
swap(arr, i, j);
i++;
j--;
}
}
return pivotIdx;
}
}