templated fuction pointers

Started by
1 comment, last by Fruny 17 years, 6 months ago
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.

#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;
}

Advertisement
quickSort<int>(array, 0, 8, compareLess);
Double post, by the way.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement