Here comes my first reading notes for C++ How to Program 7/e, which is in detail and inspire me a lot. After abandoning the book for long, now I pick up it again and start reading it fromChapter 8: Pointers. I will continuously update this blog to share what I learn with you from now on.
OK… My friend Jeff always says, “Talk is cheap. Show me your code.” In this reading notes, I will try my best to include more code and less nosense sentences. This may be the first time and the only time you see so many useless text! LOL
Here comes an example code of selection sort explaining function pointer from the book. I have slightly modified it to make it clearer.
By the way, the time complexity of selection sort is of O(n^2). So it is just useful in demonstration but not in practical program!
#include <iostream>
#include <iomanip>
using namespace std;
void printArray( int[], const int );
void selectionSort( int[], const int, bool (*)(int,int) ); // size does not change
void swap( int * const, int * const ); // pointer does not change
bool ascending( int, int );
bool descending( int, int );
int main()
{
const int arraySize = 10;
int order; // 1=ascending 2=descending
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
printArray( a, arraySize );
cout << "\nEnter 1 to sort the array in ascending order\n"
<< "Enter 2 to sort in descending order: ";
cin >> order;
if( order == 1 )
{
selectionSort( a, arraySize, ascending );
cout << endl << "Data has been sorted in ascending order." << endl;
}
else
{
selectionSort( a, arraySize, descending );
cout << endl << "Data has been sorted in ascending order." << endl;
}
printArray(a, arraySize );
return 0;
}
void printArray( int a[], const int size )
{
for( int i=0; i<size; i++ )
{
cout << setw(4) << left << a[i];
}
cout << endl;
}
void selectionSort( int a[], const int size, bool (*compare)(int,int) )
{
int smallestOrLargest; // index of the smallest(or largest) element
// loop to find index of the element to be placed at i (smallest/largest)
for( int i=0; i<size; i++ )
{
smallestOrLargest = i;
for( int j=i+1; j<size; j++ )
{
if( !(*compare)(a[smallestOrLargest], a[j]) ) // the two element not in order
{
smallestOrLargest = j;
}
}
swap( &a[i], &a[smallestOrLargest] ); // pass by reference
}
}
void swap( int * const elementPtr1, int * const elementPtr2 )
{
int temp = *elementPtr1;
*elementPtr1 = *elementPtr2; // dereference variable is a lvalue
*elementPtr2 = temp;
}
bool ascending( int a, int b )
{
return (a<b);
}
bool descending( int a, int b )
{
return (a>b);
}