#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
template <typename Any>
void quickSort(Any ar[], int start, int end, bool (*compare)(Any a, Any b));
template <typename Any>
bool compareLess(Any a, Any b);
template <typename Any>
bool compareGreater(Any a, Any b);
int _tmain(int argc, _TCHAR* argv[])
{
int array[8];
srand(time(0));
for (int i = 0; i < 8; i++)
array = rand()%20;
cout << "elements before sort lessthan" <<'\n';
for (int i = 0; i < 8; i++)
cout << array << '\n';
quickSort(array, 0, 8, compareLess);
cout << "elements after sort lessthan" <<'\n';
for (int i = 0; i < 8; i++)
cout << array << '\n';
quickSort(array, 0, 8, compareGreater);
cout << "elements after sort greaterthan" <<'\n';
for (int i = 0; i < 8; i++)
cout << array << '\n';
return 0;
}
template <typename Any>
void quickSort(Any ar[], int start, int end, bool (*compare)(Any a, Any b))
{
int pivot;
int low = start;
int high = end-1;
pivot = high-low>>1;
if (low > high)
return;
while(low < high)
{
while ((*compare)(ar[low], ar[pivot]) && low < high)
low++;
while (!(*compare)(ar[high], ar[pivot]) && low < high)
high--;
if (!(*compare)(ar[low], ar[high]))
{
int temp = ar[low];
ar[low] = ar[high];
ar[high] = temp;
}
}
quickSort(ar, start+1, pivot, compare);
quickSort(ar, pivot, end-1, compare);
return;
}
template <typename Any>
bool compareLess(Any a, Any b)
{
return a < b;
}
template <typename Any>
bool compareGreater(Any a, Any b)
{
return a > b;
}
templated fuction pointers
im having some trouble passing templated function pointers to my quicksort function. Any ideas? also dont copy my quicksort yet as theres still a bug somtimes.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement