Skip to content

Instantly share code, notes, and snippets.

@allen501pc
Created April 26, 2009 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allen501pc/102020 to your computer and use it in GitHub Desktop.
Save allen501pc/102020 to your computer and use it in GitHub Desktop.
/* Usage: To implement a function pointer with asc() , desc()
* Author: Allen (allen501pc@hotmail.com)
* Date: 04/26/2009
* Output:
* Sorted number list.
*/
#include <iostream>
using namespace std;
bool asc(int *,int *);
bool desc(int *,int *);
void mysort(int *,size_t,bool (*)(int *, int *));
void print(int [],size_t);
int main(int argc,char * argv[])
{
int iarray[10]={3,4,7,9,8,2,5,1,6,10};
mysort(iarray,10,desc); // sort by desc
print(iarray,10);
mysort(iarray,10,asc); // sort by asc
print(iarray,10);
}
bool asc(int * a,int * b)
{
int temp_int;
if(*a>*b)
{
temp_int=*a;
*a=*b;
*b=temp_int;
return true;
}
return false;
}
bool desc(int * a,int * b)
{
int temp_int;
if(*a<*b)
{
temp_int=*a;
*a=*b;
*b=temp_int;
return true;
}
return false;
}
void mysort(int * iarray,size_t size,bool (*func)(int *,int *))
{
size_t i;
bool swapped;
do
{
swapped=false;
for(i=0;i<size-1;i++)
{
if((*func)(&iarray[i],&iarray[i+1]))
swapped=true;
}
}while(swapped);
}
void print(int * iarray,size_t size)
{
size_t i;
cout << "The array cotent is..." << endl;
for(i=0;i<size;i++)
{
cout << "array[" << i+1 << "] = " << iarray[i] << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment