-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.cpp
62 lines (58 loc) · 1.18 KB
/
QuickSort.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
#include <iostream>
#include <ctime>
using namespace std;
int RandomizedPartition(int * a, int start, int end)
{
int i, j, temp;
srand(int(time(0)));
i = rand()%(end-start+1) + start;
temp = a[i];
a[i] = a[start];
a[start] = temp;
i = start+1;
j = end;
while (true)
{
while(a[j] > a[start]) j--;
while(i < j && a[i] <= a[start]) i++;
if (i >= j) break;
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
temp = a[j];
a[j] = a[start];
a[start] = temp;
return j;
}
void QuickSort(int * a, int start, int end)
{
if (start >= end)
return;
int i = RandomizedPartition(a, start, end);
QuickSort(a, start, i-1);
QuickSort(a, i+1, end);
}
int main()
{
int n, * a;
while (cin >> n)
{
if (n == 0)
break;
a = new int[n];
srand(int(time(0)));
for (int i = 0; i < n; i++)
{
a[i] = rand();
cout << a[i] << " ";
}
cout << endl;
QuickSort(a, 0, n-1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
delete [] a;
}
return 0;
}