-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort3.cpp
More file actions
61 lines (44 loc) · 1.16 KB
/
Copy pathquicksort3.cpp
File metadata and controls
61 lines (44 loc) · 1.16 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
#include <iostream>
using namespace std;
template <class DataType>
void partition(DataType theArray[], int first, int last, int &pivotIndex, int N) {
DataType pivot = theArray[last]; // copy pivot
int i = first; // index of last item in S1
int j = first; //index of 1st item in unknown
for (; j <= last; ++j) {
if (theArray[j] < pivot) { // belongs to S1
swap(theArray[j], theArray[i]);
++i;
} // else belongs to S2
}
swap(theArray[last], theArray[i]);
pivotIndex = i;
for(int i=0; i<N; i++)
cout<<theArray[i]<<" ";
cout<<endl;
} // end partition
template <class DataType>
void quicksort(DataType theArray[], int first, int last, int N) {
int pivotIndex;
if (first < last) {
// create the partition: S1, pivot, S2
partition(theArray, first, last, pivotIndex, N);
// sort regions S1 and S2
quicksort(theArray, first, pivotIndex-1, N);
quicksort(theArray, pivotIndex+1, last, N);
}
}
int main()
{
int N;
cin>>N;
int array[N];
for(int i=0; i<N; i++)
{
int temp;
cin>>temp;
array[i] = temp;
}
quicksort(array, 0, N-1, N);
return 0;
}