In: Computer Science
Reimpelment a function called bubble_sort that has the following prototype.
bubble_sort(int *array, int size, pointer to a function)
Pre condition
array - a pointer to a an array of size element.
pointer to function - a pointer to a function that compares two
values (depending on sorting in ascending order or descending
order)
Post condition
Sort the array in ascending or descending based on the the pointer
to a function.
Call the function bubble_sort to sort the array in
ascending
Display the sorting array.
Call the function bubble_sort to sort the array in descending
Display the sorting array.
use a list of integers from a file called data.txt
Here is the content of the file data.txt.
9
8
4
7
2
9
5
6
1
3
IDE Used: Dev C++
Note: For sorting in descending order, the step has been mentioned as a comment inside bubble_sort function just above if statement
Program
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//function to compare the numbers will return true if
first>second
bool compare(int x, int y)
{
   bool status;
   if(x>y)
   {
       status=true;
   }
   else
   {
   status=false;  
   }
   return status;
}
//bubble sort function
void bubble_sort(int *arr, int size, bool (*func_ptr)(int,
int))
{
int i, j,temp;
  
//pointer to function compare()
func_ptr= compare;
  
   for (i = 0; i < size; i++)   
{
  
  
for (j = 0; j < size-i-1; j++)
  
       //calling the compare() function
using pointer
       //for descending order
sorting use if((*func_ptr)(arr[j+1],arr[j]))
if ((*func_ptr)(arr[j+1],arr[j]))
{
   //swapping the value if condition true
       temp = arr[j];
          
arr[j]=arr[j+1];
           arr[j+1]=
temp;
          
  
       }
}
}
int main()
{
   FILE *file;
  
   //opening the file
   file = fopen("data.txt", "r");
   int i =0;
   int x ;
   int size;
   int arr[20];
   int *arr_ptr = arr;
   void (*func_ptr);
   while(!feof(file))
   {
       //reading the file
       fscanf(file, "%d",&x);
      
       //stroing the file data in
array
       arr[i]=x;
       i++;
   }
   size=i;
  
   //calling the bubble sort function
   bubble_sort(arr_ptr,size, func_ptr);
  
   //printing the sorted array
   printf("Sorted array using bubble sort\n");
   for (i = 0; i < size; i++)
printf("%d, ",arr[i]);
  
   //closing the file
   fclose(file);
   return 0;
}
Output for ascending

Output in descending

Sorted array using bubble sort , 2, 3, 4, 5, 6, 7, 8, 9, 9, Process exited after 0.07594 seconds with return value 0 Press any key to continue
Sorted array using bubble sort 9. 9 8 7. 6 5, 4, 3 2, 1, Process exited after 0.04748 seconds with return value 0 Press any key to continue
Data.txt
9
8
4
7
2
9
5
6
1
3