Monday, 18 September 2017

Q- Sort


Qsort is a C standard library function that implements a polymorphic sorting algorithm for arrays of arbitrary objects according to a user-provided comparison function. It is named after the "quicker sort" algorithm (a quick sort variant due to R. S. Scowen), which was originally used to implement it in the Unix C library, although the C standard does not require it to implement quicksort.

Implementations of the qsort function achieve polymorphism, the ability to sort different kinds of data, by taking a function pointer to a three-way comparison function, as well as a parameter that specifies the size of its individual input objects. The C standard requires the comparison function to implement a total order on the items in the input array.

A qsort function was in place in Version 3 Unix of 1973, but was then an assembler subroutine. A C version, with roughly the interface of the standard C version, was in-place in Version 6 Unix.It was rewritten in 1983 at Berkeley. The function was standardized in ANSI C (1989).


Source : wiki qsort

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

/* Comparison function. Receives two generic (void) pointers to the items under comparison. */
int compare_ints(const void *p, const void *q) 
{
       int x = *(const int *)p;
       int y = *(const int *)q;
 
    /* Avoid return x - y, which can cause undefined behaviour because of signed integer overflow. */
       if (x < y)
             return -1;  // Return -1 if you want ascending, 1 if you want descending order.
       else if (x > y)
             return 1;   // Return 1 if you want ascending, -1 if you want descending order.
    return 0;
}

/* Sort an array of n integers, pointed to by a. */

void sort_ints(int *a, size_t n) 
{
    qsort(a, n, sizeof *a, &compare_ints);
}

int main()
{

    int n,i;
          scanf("%d",&n);
   
    int a[n];
    for(i=0;i<n;i++)
    {
          scanf("%d",&a[i]);
    }
    sort_ints(a,n);
    for(i=0;i<n;i++)
          printf("%d ",a[i]);
   
    return 0;
}

[  qsort(a, n, sizeof *a, &compare_ints);   ]
a                       - This is the pointer to the first element of the array to be sorted.
n                       - This is the number of elements in the array pointed by base.
sizeof*a           - This is the size in bytes of each element in the array. 

compare_ints   - This is the function that compares two elements.

Output :

 


 

No comments:

Post a Comment