0% found this document useful (0 votes)
37 views4 pages

Ques.: Passing Ascending and Descending Function As Argument

The document discusses passing ascending and descending functions as arguments to a bubble sort function. An array of numbers is sorted in either ascending or descending order depending on user input by calling the bubble sort function and passing the appropriate comparison function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views4 pages

Ques.: Passing Ascending and Descending Function As Argument

The document discusses passing ascending and descending functions as arguments to a bubble sort function. An array of numbers is sorted in either ascending or descending order depending on user input by calling the bubble sort function and passing the appropriate comparison function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

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:-

You might also like