From 62a2a4cec56a43d061bea5a4f1be57f368a1c905 Mon Sep 17 00:00:00 2001 From: Rohit Bindal Date: Fri, 22 Oct 2021 18:42:43 +0530 Subject: [PATCH] Create randomized_quickf_sort.cpp --- .../Sorting/randomized_quickf_sort.cpp | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 dsa-roadmaps/Beginners/Algorithms/Sorting/randomized_quickf_sort.cpp diff --git a/dsa-roadmaps/Beginners/Algorithms/Sorting/randomized_quickf_sort.cpp b/dsa-roadmaps/Beginners/Algorithms/Sorting/randomized_quickf_sort.cpp new file mode 100644 index 0000000..5f1d6d8 --- /dev/null +++ b/dsa-roadmaps/Beginners/Algorithms/Sorting/randomized_quickf_sort.cpp @@ -0,0 +1,82 @@ +#include +using namespace std; + +//if we apply quick sort on array of random elements then it takes time O(nlogn) +//if we apply quick sort on already sorted array then it takes O(n*2), in this case +//first we shuffle the elements of array randomly and then apply quick sort +//this is also knows as Randomised Quick Sort. + +void shuffleRandomly(int *a, int s, int e) +{ + srand(time(NULL)); + int i,j,temp; + for(j=e; j>0 ; j--) + { + i = rand()%(j+1); + swap(a[i], a[j]); + } +} + +int partition(int *a, int s, int e) +{ + //it will return the index of pivot element + + int i = s-1; + int j = s; + //consider pivot element to be last one + int pivot = a[e]; + + for( ;j=e) + return; + + int pivot = partition(a,s,e); + + //the we have to sort two arrays i.e. array left to the pivot and array right to the pivot + + quickSort(a,s,pivot-1); + quickSort(a,pivot+1,e); + + +} + + +int main() +{ + + int a[]={8,15,20,22,25,26,30,32,36,40}; + int s = 0; + //initially consider the pivot element to be the last one + int e = sizeof(a)/sizeof(int)-1; + shuffleRandomly(a,s,e); + cout<<"Randomly Shuffled Array: "; + for(int i=0 ; i<=e;i++) + { + cout<