ascending array with a template

I've combined an ascending function into a template but its not sorting all the numbers.

The lines of code are:


#include <iostream>
#include <iomanip>
using namespace std;


template< typename T >
void selectionSort( int [], const int, int (*)( int, int ) );
void swap( int * const, int * const );
int ascending( int, int );


	void selectionSort( int work[], const int size, int (*compare)( int, int ) )
	{
		int smallestToLargest;

		for ( int i = 0; i < size - i; ++i )
		{
			smallestToLargest = i;

			for ( int index = i + 1; index < size; ++index )
			if ( !(*compare)( work[ smallestToLargest ], work[ index ] ) )
				smallestToLargest = index;
		swap( &work[ smallestToLargest ], &work[ i ] );
		}
	}
	void swap( int * const element1Ptr, int * const element2Ptr )
	{
		int hold = *element1Ptr;
		*element1Ptr = *element2Ptr;
		*element2Ptr = hold;
	}

int ascending( int a, int b )
{
	return a < b;
}


int main()
{
	const int arraySize = 10;
	int order;
	int counter;
	int a[ arraySize ] = { 2, 6, 4, 58, 10, 12, 89, 68, 45, 37 };

	cout << "\nData items in original order\n";
		for ( counter = 0; counter < arraySize; ++counter )
			cout<< setw( 4 ) << a[ counter ];

	cout << "\nData items in ascending order\n";

	selectionSort( a, arraySize, ascending );
	
	for ( counter = 0; counter < arraySize; ++counter )
		cout << setw( 4 ) << a[ counter ];

	cout << endl;

}


Whats supposed to happen is the array of numbers will sort smallest to largest but it only sorts the first 6 numbers and the last 4 are out of place.

So my question is did I miss a line or just mistype a line?
closed account (o3hC5Di1)
Hi there,

Not entirely sure about this - no expert here.
However, this line seems strange to me:

for ( int i = 0; i < size - i; ++i )

It means that when i becomes 6 the condition will not hold true any more (6 > 10-6), so the first six iterations (0 to 5) are carried out, then the loop stops.

Hope that helps.

All the best,
NwN
Oh crap. Completely missed that. Took it out and now runs perfectly.

Thanks
Besides that, what's the point in creating a templated function if you don't use Templated types inside it? You should change your "int"s in "T"s, except for some loops, but I'm sure you will be able to figure it out.
Topic archived. No new replies allowed.