forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick_Sort.cpp
84 lines (62 loc) · 2.25 KB
/
Quick_Sort.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
74
75
76
77
78
79
80
81
82
83
#include<iostream> //Header file
using namespace std; //For cin and cout
/*
Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array
and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot.
The sub-arrays are then sorted recursively. This can be done in-place, requiring small additional amounts of memory to perform the sorting.
@author Aditya Saxena
@since 27-6-2020
*/
//Implement partitionPivot function
int partitionPivot( int a[], int start, int end ){
int i= start-1;
int j= start;
int pivot= a[end];
//Traverse the array - whenever an element smaller than pivot occurs, swap it with (i+1)th element
for(j= start; j<= end-1; j++){
if(a[j] <= pivot){
i++;
swap(a[i],a[j]);
}
}
//Place the pivot element at i+1 (between smaller and larger elements)
swap(a[i+1],a[end]);
//Return position of pivot
return i+1;
}
//Implement Quick Sort function
void quickSort( int a[], int start, int end ){
//base case
//If start (index) crosses end (index), there are no elements to sort further, thus return
if( start >= end ){
return;
}
//Taking end element as pivot, place the pivot element in its right position such that
//elements left to the pivot are smaller than pivot and elements right to the pivot are greater than pivot
//Return pivot's position (index)
int p= partitionPivot( a, start, end );
//Recursively sort left and right part of the pivot element
//Left part of the pivot
quickSort( a, start, p-1 );
//Right part of the pivot
quickSort( a, p+1, end);
return;
}
int main(){
int n;
cout<<"Enter the number of elements: ";
cin>>n;
int a[n];
cout<<endl<<"Enter the elements of the array: ";
for(int i= 0; i<n; i++){ //For loop to input n elements into the array
cin>>a[i];
}
//Call the quick sort function on the array - quickSort( array_name, start, end);
quickSort( a, 0, n-1 );
//Print the sorted array
cout<<endl<<"The sorted array is: ";
for(int i= 0; i< n; i++){
cout<<a[i]<<" ";
}
return 0;
}