Thread: Qsort

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    3

    Qsort

    I saw this example on a website:

    Code:
    /* qsort example */
    #include <stdio.h>
    #include <stdlib.h>
    
    int values[] = { 40, 10, 100, 90, 20, 25 };
    
    int compare (const void * a, const void * b)
    {
      return ( *(int*)a - *(int*)b );
    }
    
    int main ()
    {
      int * pItem;
      int n;
      qsort (values, 6, sizeof(int), compare);
      for (n=0; n<6; n++)
      {
        printf ("%d ",values[n]);
      }
      return 0;
    }
    I understand all of it but the compare function. Could someone explain to me in simple terms what the compare function is doing?

    Thanks,

    Shane

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    That compare function is subtracting a from b. First it casts each void * as an int *, and then dereferences them. The end result is a positive integer if a > b, 0 if a = b, and a negative integer if a < b.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Except it's safer to write it out in a slightly longer form
    Code:
    int compare (const void * a, const void * b)
    {
      int v1 = *(int*)a;
      int v2 = *(int*)b;
      if ( v1 < v2 ) return -1;
      if ( v1 > v2 ) return +1;
      return 0;
    }
    A simple subtraction has the possibility of underflow, and thus the possibility of producing the wrong answer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    3
    Thanks to both of you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An interesting problem of qsort()
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 03-05-2008, 12:09 PM
  2. qsort() in Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 8
    Last Post: 06-16-2007, 04:18 PM
  3. trouble with qsort
    By qubit67 in forum C Programming
    Replies: 5
    Last Post: 04-29-2007, 10:23 PM
  4. Question About Using qsort
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 11-04-2003, 03:17 PM
  5. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 02:22 AM