forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomized_Quick_Sort.cpp
106 lines (77 loc) · 2.73 KB
/
Randomized_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<iostream> //Header file
#include<ctime> //To use time function as a seed for pseudo random generator
#include<cstdlib> //For pseudo random number generator
using namespace std; //For cin and cout
/*
In Randomized Quick Sort, we use random number to pick the next pivot (or we randomly shuffle the array)
and then apply quick sort on the array. Randomization is used here to eliminate the worst case time complexity
of quick sort (that is, when the input array is already sorted).
@author Aditya Saxena
@since 27-7-2020
*/
//Implemention randomShuffle function
void randomShuffle( int a[], int start, int end ){
//Seed time to the pseudo random number generator
srand( time( NULL ) );
int i, j;
//Generate random number and bring them to range 0 to i+1 and store in j
//Swap element at ith and jth index
for( i= end; i >= 0; i-- ){
j= rand() % ( i + 1 );
swap(a[j],a[i]);
}
}
//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];
}
//Shuffle the array
randomShuffle( a, 0, n-1);
//Call the quick sort function on the array - quickSort( array_name, start, end);
quickSort( a, 0, n-1 );
//Print the sorted array
for(int i= 0; i< n; i++){
cout<<a[i]<<" ";
}
return 0;
}