-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathQuickSort.cpp
73 lines (64 loc) · 1.24 KB
/
QuickSort.cpp
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
// Quick Sort
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
void printArray(int arr[],int size)
{
for(int i=0;i<size;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int partition(int arr[],int low,int high)
{
int pivot = arr[low];
int start= low+1;
int end = high;
int temp;
do{
while(arr[start] <= pivot)
{
start++;
}
while(arr[end]> pivot)
{
end--;
}
if(start<end)
{
temp= arr[start];
arr[start] = arr[end];
arr[end]= temp;
}
}while(start<end);
// Swap arr[low] and arr[end]
temp = arr[low];
arr[low]= arr[end];
arr[end]=temp;
return end;
}
void quickSort(int arr[],int low,int high)
{
int partiitionindex;
if(low<high)
{
partiitionindex = partition(arr,low,high);
quickSort(arr,low,partiitionindex-1);
quickSort(arr,partiitionindex+1,high);
}
}
int main()
{
int n;
cout<<"Enter the size of the array:";
cin>>n;
int A[n];
cout<<"Enter "<<n<<" elements:";
for(int i=0;i<n;i++)
{
cin>>A[i];
}
printArray(A,n);
quickSort(A,0,n-1);
printArray(A,n);
return 0;
}