-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedQuickSort.cpp
More file actions
64 lines (55 loc) · 1.09 KB
/
RandomizedQuickSort.cpp
File metadata and controls
64 lines (55 loc) · 1.09 KB
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
#include <iostream>
#include <ctime>
using namespace std;
int randIntRange(int s, int e)
{
// returns a random number in range [s, e]
return (1 + rand() % e);
}
void shuffel(int *arr, int e)
{
for(int i = 0; i < e; i++)
{
swap(arr[i], arr[randIntRange(i+1, e)]);
}
}
int partition(int *arr, int s, int e)
{
int pivot = arr[e];
int i = s - 1;
for(int j = s; j < e; j++)
{
if(arr[j] < pivot)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[e]);
return i + 1; // current pivot index
}
void quickSortHelper(int *arr, int s, int e)
{
// Base Case
if(s >= e)
return;
int p = partition(arr, s, e); // pivot index
quickSortHelper(arr, s, p-1);
quickSortHelper(arr, p+1, e);
}
void quickSort(int* arr, int s, int e)
{
shuffel(arr, e);
quickSortHelper(arr, s, e);
}
int main()
{
srand(time(NULL));
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
quickSort(arr, 0, 9);
cout << "After Sorting" << endl;
for(int i : arr)
{
cout << i << " ";
}
}