C program to sort an array using qsort() functions.

#include <stdio.h>
#include <stdlib.h>


int cfun(const void * a , const void * b)
{
  int x =  *(const int * )a;
  int y =  *(const int * )b;
  
  if(x<y)
    return -1;
  
  if(x>y)
     return 1;
     
   return 0;  

}


int main()
{
    
	int i;
    int arr[] = {10,20,4,19,54};  

	printf("Array before sorting : \n");
	
	for(i=0;i<5;i++)
	{
    	printf("%d  ",arr[i]);
	}
	
	 qsort(arr,5, sizeof(int), cfun);
     
     /*
	   qsort(arg1,arg2,arg3,arg4);
	   
	   arg1 >> array to sort
	   arg2 >> total no. of elements
	   arg3 >> sizeof elements
	   arg4 >> comparator function
	 
	 */

	printf("\nArray after sorting : \n");
	
	for(i=0;i<5;i++)
	{
    	printf("%d  ",arr[i]);
	}

		
	return 0;
}
OUTPUT:

Array before sorting :
10  20  4  19  54
Array after sorting :
4  10  19  20  54  

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *