-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathQuick sort.cpp
More file actions
46 lines (37 loc) · 929 Bytes
/
Quick sort.cpp
File metadata and controls
46 lines (37 loc) · 929 Bytes
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
#include<iostream>
using namespace std;
//Partition returns the address of the pivot or the partition point
int partition(int arr[], int start, int end)
{
int pivot = end; // selecting the last element as the pivot
for(int i=0; i<end-1; i++)
if(arr[i] >= arr[pivot])
{
int temp = arr[i];
arr[i] = arr[pivot];
arr[pivot] = temp;
}
return pivot;
}
void quicksort(int arr[], int start, int end)
{
if(start >= end)
return;
int partitionIndex = partition(arr, start, end);
//recursive calls
quicksort(arr, start, partitionIndex - 1);
quicksort(arr, partitionIndex + 1, end);
}
int main()
{
int arr[] = {3,5,7,9,8,6,4,1,2,10};
int length = sizeof(arr)/sizeof(arr[0]);
cout<<"Unsorted: ";
for(int i=0; i<length; i++)
cout<<arr[i]<<" ";
cout<<endl;
quicksort(arr, 0, length);
cout<<"\nSorted: ";
for(int i=0; i<length; i++)
cout<<arr[i]<<" ";
}