-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.cpp
64 lines (54 loc) · 1.35 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
63
64
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<iomanip>
using namespace std ;
int EASYQUICK(int A[], int start, int end ) ; // first int is dclare an array,
//second int declare the start position,
//The third int declare the end position.
int main()
{
// quicksort
srand(time(0)) ; // random seed
const int m = 10 ;
int Array[m] = {} ;
for ( int i = 0 ; i<m ; i++) Array[i] = rand()/10 ; // build up a random array
cout << "The original array is :" << endl ;
cout << setw(6) ;
for ( int i = 0 ; i<m ; i++) cout << Array[i] << " " ;
cout << endl ;
EASYQUICK( Array , 0 , m-1 ) ;
cout << "The sorted array is :" << endl ;
cout << setw(6) ;
for ( int i = 0 ; i<m ; i++) cout << Array[i] << " " ;
cout << endl ;
return 0 ;
}
int EASYQUICK(int A[], int start, int end )
{
if ( end - start > 0 )
{
int pivot = A[end] ;
int B [end-start+1] ;
for ( int i = start ; i <= end ; i++) B[i] = 0 ;
int head=start, tail=end ;
for ( int i = start ; i< end ; i++)
{
if ( A[i] < pivot )
{
B[head] = A[i] ;
head ++ ;
}
else
{
B[tail] = A[i] ;
tail -- ;
}
}
int median = head ;
B[median] = pivot ;
for ( int i = start ; i<= end ; i++ ) A[i] = B[i] ;
if ( head >start) EASYQUICK(A,start,median-1) ;
if ( tail <end) EASYQUICK(A,median+1,end) ;
}
}