Ques.
Passing ascending and descending
function as argument :-
=> #include <stdio.h>
#define SIZE 10
void bubbleSort( int * const array, const int size,int(*compare)(int
a,int b));
int ascending(int a,int b);
int descending(int a,int b);
int main()
{
int choice;
int i;
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
printf( "Data items in original order\n" );
for ( i = 0; i < SIZE; i++ ) {
printf( "%4d", a[ i ] );
}
printf("\nEnter 1 to sort in ascending order\nEnter 2 to sort in
descending order\n");
scanf("%d",&choice);
if(choice == 1){
bubbleSort(a, SIZE, ascending);
}else if(choice == 2){
bubbleSort(a, SIZE, descending);
}else{
printf("invalid input");
}
printf( "\nData items in sorted order\n");
for ( i = 0; i < SIZE; i++ )
{
printf( "%4d", a[ i ] );
}
printf( "\n" );
return 0;
}
void bubbleSort( int * const array, const int size, int(*compare)(int
a,int b))
{
int pass;
int j;
void swap( int *element1Ptr, int *element2Ptr );
for ( pass = 0; pass < size - 1; pass++ ) {
for ( j = 0; j < size - 1; j++ ) {
if((*compare)(array[ j ],array[ j + 1 ])){
swap( &array[ j ], &array[ j + 1 ] );
}
}
}
}
void swap( int* element1Ptr, int* element2Ptr)
{
int temp = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = temp;
}
int ascending(int a,int b){
return a > b;
}
int descending(int a,int b){
return a < b;
}
ScreenShot:-