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
|
#include <iostream>
#include <limits>
using namespace std;
unsigned long long comparisons = 0;
unsigned long long swaps = 0;
bool comp_less(int a, int b){
++comparisons;
if ( comparisons == numeric_limits<unsigned long long>::max() )
{
std::cout << "Number of comparisons reached max value. Resetting it 0.\n";
swaps = 0;
}
return a < b;
}
void swap(int& a, int& b)
{
++swaps;
if ( swaps == numeric_limits<unsigned long long>::max() )
{
std::cout << "Number of swaps reached max value. Resetting it 0.\n";
swaps = 0;
}
int t = a;
a = b;
b = t;
}
int *partition(int *first, int *last)
{
int *pivot = last - 1;
int *i = first;
int *j = last - 1;
for (;;)
{
while (comp_less(*i, *pivot) && i < last)
{
++i;
}
while (*j >= *pivot && j > first)
{
--j;
}
if (i >= j)
break;
swap(*i, *j);
}
swap(*(last - 1), *i);
return i;
}
void quickSort(int* first, int* last) {
{
if ((first - last) <= 1)
return;
int *pivot = partition(first, last);
quickSort(first, pivot);
quickSort(pivot + 1, last);
}
}
int main( ) {
int a[] = { 1, 4, 6, 1, 3, 4, 8, 22 };
quickSort(a,a+8);
cout << a[4] << endl;
cout << comparisons << endl;
cout << swaps << endl;
}
|