-
Notifications
You must be signed in to change notification settings - Fork 1
/
randomized_quick_sort.cpp
68 lines (58 loc) · 1.48 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
#include <vector>
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int partition(vector<int> &arr, int left, int right)
{
// Finding random element in range [left, right]
int random_number = left + (rand() % (right - left + 1));
// Swap random element with the last element so we can apply our simple quicksort
swap(arr[random_number], arr[right]);
// Normal quicksort
int i = left - 1, x = arr[right];
for (int j = left; j <= right - 1; j++)
{
if (arr[j] <= x)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[right]);
return i + 1;
}
void randomized_quick_sort(vector<int> &arr, int left, int right)
{
if (left < right)
{
// Finding pivot element
int pivotIndex = partition(arr, left, right);
// D&C
randomized_quick_sort(arr, left, pivotIndex - 1);
randomized_quick_sort(arr, pivotIndex + 1, right);
}
}
int main()
{
// Generate random number every time
srand((unsigned)time(NULL));
// Given array
vector<int> arr = {1, 2, 4, 1, 5, 4, 7, 5, 9, 4};
int n = arr.size();
cout << "Original Array: ";
for (auto x : arr)
{
cout << x << " ";
}
cout << endl;
// Sorting the array using ranomized quicksort algorithm
randomized_quick_sort(arr, 0, n - 1);
cout << "Sorted Array: ";
for (auto x : arr)
{
cout << x << " ";
}
cout << endl;
return 0;
}