-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort-using-Recursion.cpp
More file actions
72 lines (58 loc) · 1.49 KB
/
Copy pathquickSort-using-Recursion.cpp
File metadata and controls
72 lines (58 loc) · 1.49 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
#include<iostream>
using namespace std;
int partition(int arr[],int s,int e)
{
//Taking first element as pivot
int pivot=arr[s];
// Count elements smaller than pivot
int cnt=0;
for (int i = s+1; i <= e; i++)
{
if (arr[i]<=pivot)
cnt++;
}
// Finding right place/position for pivot
int pivotIndex = s+cnt;
// Swapping to place pivot at its right position
swap(arr[pivotIndex],arr[s]);
// handle left and right part
// We want lesser elements to be on the left side of the pivot
// and greater elements to be on the right side of the pivot
int i= s;
int j= e;
while (i < pivotIndex && j > pivotIndex)
{
//Already sorted elements of left side
while (arr[i]<=pivot)
i++;
//Already sorted elements of right side
while (arr[j]>pivot)
j--;
if (i < pivotIndex && j > pivotIndex )
swap(arr[i++],arr[j--]);
}
return pivotIndex;
}
void quickSort(int arr[],int s,int e)
{
//Base Case
if(s>=e)
return;
//partition krdo
int pIndex= partition(arr,s,e);
//left ko sort krdo
quickSort(arr,s,pIndex-1);
//right ko sort krdo
quickSort(arr,pIndex+1,e);
}
int main()
{
int arr[]={12,11,13,5,6,7,7,7};
int size=8;
quickSort(arr,0,size-1);
for (int i = 0; i < size; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}