Created
April 26, 2009 11:57
-
-
Save allen501pc/102020 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Usage: To implement a function pointer with asc() , desc() | |
* Author: Allen ([email protected]) | |
* 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