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 79 80 81 82 83 84 85 86 87
|
#include <iostream>
using namespace std;
template <class T>
void QuicksortHelper(T arr[], int low, int high,int &counter);
template <class T>
int QSPartition(T arr[], int low, int high,int &counter);
//n is the size of array
template <class T>
int Quicksort(T arr[], int n)
{
int count = 0;
QuicksortHelper(arr, 0, n - 1,count);
return count;
}
template <class T>
void QuicksortHelper(T arr[], int low, int high,int &counter)
{
if (low < high) {
int partitionLocation = QSPartition(arr, low, high,counter);
QuicksortHelper(arr, low, partitionLocation,counter);
QuicksortHelper(arr, partitionLocation + 1, high,counter);
}
}
//parition works
template <class T>
int QSPartition(T arr[], int low, int high,int &counter)
{
int pivotindex = low; //set pivot index to beginning of subarray
T pivot = arr[high]; //stores the number of the last element in arr
for (int j = low + 1; j < high; j++) {
counter++;
if (arr[j] <= pivot) {
//swap pivotindex and j
T temp = arr[pivotindex];
arr[pivotindex] = arr[j];
arr[j] = temp;
//end of swap
pivotindex++;
}
}
//swap last element with pivotindex
// if(pivotindex == (high - 1)){
// //...Do nothing
// } else
if (arr[pivotindex] > arr[high]){
T temp2 = arr[pivotindex];
arr[pivotindex] = arr[high];
arr[high] = temp2;
}
cout << "Pivot Returned:" << pivotindex << endl;
return pivotindex;
}
void Test_Quicksort() {
std::cout << "Original array:" << std::endl;
int size = 9;
int arr[size] = { 7,2,1,6,8,5,3,4,0};
//Print array
for (int i = 0; i <size; i++) {
std::cout << arr[i] << ',';
}
std::cout << std::endl;
Quicksort(arr, size);
//Print array
for (int i = 0; i < size; i++) {
std::cout << arr[i] << ',';
}
std::cout << std::endl;
;
}
int main()
{
Test_Quicksort();
}
|