-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
78 lines (62 loc) · 1.35 KB
/
QuickSort.cpp
File metadata and controls
78 lines (62 loc) · 1.35 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//Quick Sort
//partition:for some j, entry a[j] is in place, make no larger entry to the left of j,
//no smaller entry to the right of j
//sort each piece
//time: O(nlgn) compares, O(nlgn) exchanges
//not stable
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define SORT_NUM 50
void swap(int *a,int m,int n)
{
int tmp = a[m];
a[m] = a[n];
a[n] = tmp;
}
void display(int *a,int num)
{
for(int i=0;i<num;i++)
cout << "sorted array [" << i << "] = " << a[i] << endl;
}
int Partition(int *a,int lo,int hi) //recursion call itself
{
int i = lo;
int j = hi+1;
while(1)
{
while(a[++i]<a[lo])
if(i == hi) break;
while(a[lo]<a[--j])
if(j == lo) break;
if(j<=i) break;
swap(a,i,j);
}
swap(a,lo,j);
return j;
}
void QuickSort(int *a,int lo,int hi)
{
if(lo<hi)
{
int part = Partition(a,lo,hi);
QuickSort(a,lo,part-1);
QuickSort(a,part+1,hi);
}
}
int main()
{
int lo = 0;
int hi = SORT_NUM-1;
int num = SORT_NUM;
int a[num]= {0};
srand((int)time(0));
for(int i=0;i<num;i++)
a[i] = rand()%100;
//display(a,num);
//cout << "-----------------------------------------------"<<endl;
QuickSort(a,lo,hi);
display(a,num);
return 0;
}