-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort2.cpp
68 lines (55 loc) · 1.04 KB
/
quicksort2.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 <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void swap(int* p1, int* p2);
void quicksort(int* arr, int start, int end);
int main()
{
int arr[10000];
int num = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < num; i++) {
arr[i] = i+1;
}
for (int i = 0; i < num; i++) {
swap(&arr[rand() % num], &arr[rand() % num]);
}
clock_t t1 = clock();
quicksort(arr, 0, num - 1);
clock_t t2 = clock();
//for (int i = 0; i < num; i++) cout << arr[i] << " ";
cout << endl;
cout << "Executed time : " << t2 - t1 << "ms" << endl;
return 0;
}
void swap(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void quicksort(int* arr, int start, int end)
{
if (start >= end) {
return;
}
int i = start + 1, j = end;
int pivot = arr[start];
while (i < j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot && j>start) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
else
{
swap(&arr[j], &arr[start]);
}
}
quicksort(arr, start, j - 1);
quicksort(arr, j + 1, end);
}