This blog is under construction

Monday 30 April 2012

qsort example in C

Header file:
    stdlib.h

Synopsis:
     void qsort(void *base, size_t num, size_t sz,
                  int(*compar)(const void *, const void *));

Description:
      It sorts the elements present in base array with num elements each of size sz.


qsort function C example:


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


  /* -ve value if *key is less than *base, +ve value if *key > *base  */
  int compare (const void *key, const void *base) {
        return(*(int *)key - *(int *)base);
  }


  int main() {
        FILE *fp;
        void *ptr;
        char *str, data[100];
        int base[100], n = -1, size, i;
        fp = fopen("file.txt", "r");

        if (fp == NULL) {
                str = strerror(errno);
                perror(str);
                return;
        }

        /* read the input values from input file */
        while(!feof(fp)) {
                fgets(data, 100, fp);
                data[strlen(data) - 1] = '\0';
                n++;
                base[n] = atoi(data);
        }
        size = sizeof(int);
        qsort((void *)base, n, size, compare);  // quick sort


        /* print the output */
        printf("Sorted values:\n");

        for (i = 0; i < n; i++)
                printf("%5d\n", base[i]);
        printf("\n");
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat file.txt
  2000
  100
  3000
  700
  1000
  50

  jp@jp-VirtualBox:~/$ ./a.out
  Sorted values:
     50
    100
    700
   1000
   2000
   3000



No comments:

Post a Comment