-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomQuickSort.cpp
64 lines (61 loc) · 1.08 KB
/
RandomQuickSort.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
#include "SortAlgorithm.h"
#include <iostream>
using namespace::std;
int* random_quick_sort(int* nums, int left, int right);
int main_random_quick_sort()
{
cout << "Random Quick sort" << endl << "n: " << endl;
int n;
cin >> n;
while (n != 0)
{
int* s = new int[n];
for (int i(0); i < n; i++)
{
cin >> s[i];
}
random_quick_sort(s, 0, n - 1);
cout << "ans:" << endl;
for (int i(0); i < n; i++)
{
cout << s[i] << " ";
}
cout << endl;
cout << "n:" << endl;
cin >> n;
}
return 0;
}
int* random_quick_sort(int* nums, int left, int right)
{
int p = left;
int q = right;
if (p >= q)
return nums;
int temp = rand() % (right - left + 1) + left;
int key = nums[temp];
nums[temp] = nums[right];
nums[right] = key;
while (true)
{
while (p < right && nums[p] <= key)
p++;
while (q > 0 && nums[q] >= key)
q--;
if (p < q)
{
int temp = nums[p];
nums[p] = nums[q];
nums[q] = temp;
}
else
{
break;
}
}
nums[right] = nums[p];
nums[p] = key;
random_quick_sort(nums, left, p - 1);
random_quick_sort(nums, p + 1, right);
return nums;
}