1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ int random (int lower, int upper){ // function to generate a random number in a given range
5
+
6
+ int num = (rand () %(upper - lower + 1 )) + lower;
7
+ return num;
8
+ }
9
+
10
+ void printArray (int * arr, int size){
11
+ for (int i = 0 ; i < size; i++) cout<<arr[i]<<" " ;
12
+ cout<<endl;
13
+ }
14
+
15
+ int partition (int * arr, int start , int end){
16
+
17
+ int index = random (start, end); // select a random index in the subarray
18
+ swap (arr[start], arr[index ]); // swap that random index with the first element of that subarray
19
+
20
+ // continue with the normal quicksort partition subroutine
21
+
22
+ int pivot = arr[start];
23
+ int i = start;
24
+
25
+ for (int j = start +1 ; j<= end; j++){
26
+ if (arr[j]<= pivot){
27
+ i++;
28
+ if (i != j) swap (arr[i], arr[j]);
29
+ }
30
+ }
31
+ swap (arr[start], arr[i]);
32
+
33
+ return i;
34
+
35
+ }
36
+
37
+ void randomized_quickSort (int * arr, int p, int r){
38
+ if (p < r){ // this line is important as it controls the recursion calls
39
+ int q = partition (arr, p , r);
40
+ randomized_quickSort (arr, p, q-1 );
41
+ randomized_quickSort (arr, q+1 , r);
42
+ }
43
+ }
44
+
45
+ int main (){
46
+ int n;
47
+ cout<<" enter the number of elements in the array: " <<endl;
48
+ cin>>n;
49
+
50
+ int arr[n];
51
+
52
+ cout<<" enter the elements: " <<endl;
53
+
54
+ for (int i = 0 ; i < n; i++)cin>>arr[i];
55
+
56
+ cout<<" the unsorted array is: " <<endl;
57
+ printArray (arr,n);
58
+
59
+ randomized_quickSort (arr, 0 , n-1 );
60
+
61
+ cout<<" the sorted array is: " <<endl;
62
+ printArray (arr, n);
63
+ }
0 commit comments