Thread: qsort help

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    8

    qsort help

    Hey guys, I'm having trouble with qsort. I just want to sort 10 numbers in ascending order. I've even copied in the code from the examples on this and other sites. The problem is that when I enter the numbers from 1-10 in that order, it sorts fine. But
    sometimes for no apparent reason(usually if I start with 10) it sorts the numbers and when I print them I get my numbers times 10 and even then it's not in order.

    Here's an example of my running program and output:

    Enter number 1: 10

    Enter number 2: 9

    Enter number 3: 8

    Enter number 4: 7

    Enter number 5: 6

    Enter number 6: 5

    Enter number 7: 4

    Enter number 8: 3

    Enter number 9: 2

    Enter number 10: 1
    1 - Ascending
    2 - Descending
    1
    10
    30
    40
    50
    60
    70
    80
    90
    20
    10

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Post your code... lets see what's going on...

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    8
    Here is my program...


    Code:
    /* Asks the operator to input 10 numbers and then presents a menu
       giving the option to sort in ascending or descending order */
    
    #include <stdio.h>
    #include <stdlib.h>
    #define MAX 1000 // max size of input array
    
    void mainMenu(void);  // show main menu 
    void getNumber(char*); // get a char from keyboard
    void convertToInt(char*, int*, int); // convert keyboard char to int
    void sortTheNumberAsc(int *); // sort the number in ascending order
    void sortTheNumberDes(int *); //sort the number in descending order
    int comparison(const void *, const void *); // used for function qsort
    int endProgram(void);
    
    
    int main()
    {
        char inputNumber[MAX] = {0}; // numbers from operator entered as chars
        int numbersToSort[MAX] = {0}; // numbers from operator after conversion to int
        int i, c, d; // i is for looping, c for character input, d for decision for asc/des
        int j = 1;  // for main program loop
        
        while (j == 1) 
        {
            mainMenu();
            for (i = 0; i < MAX; ++i) 
            {
                inputNumber[i] = 0;
                numbersToSort[i] = 0;
            }
            
            for (i = 0; i < 10; ++i) 
            {
                printf("\nEnter number %d: ", i + 1);
                getNumber(inputNumber);
                convertToInt(inputNumber, numbersToSort, i);
            }
            
            printf("1 - Ascending\n2 - Descending\n");
            while ((c=getchar()) && c != '\n' && c != EOF) 
                d = c;
            
            if (d == '1') 
                sortTheNumberAsc(numbersToSort);
            else    
                sortTheNumberDes(numbersToSort);
    
            j = endProgram();
        }
    
        
        
        
    }
    
    
    void mainMenu(void)
    {
        printf("Enter numbers one at a time and then specify ascending sort or descending sort.\n");
    }
    void getNumber(char *inputNumber)
    {
        int i, c;
        i = 0;
        while ((c= getchar()) && c != '\n' && c != EOF) 
        {
            inputNumber[i] = c;
            ++i;
        }
    }
    void convertToInt(char *inputNumber, int *numbersToSort, int i)
    {
        numbersToSort[i] = atoi(inputNumber);
    }
    void sortTheNumberAsc(int *numbersToSort)
    {
        int i;
        qsort(numbersToSort, sizeof(numbersToSort), sizeof(numbersToSort[0]), comparison);
        for (i = 0; i <10; ++i)
            printf("%d\n", numbersToSort[i]);
    }
    void sortTheNumberDes(int *numbersToSort)
    {
        int i;
        qsort(numbersToSort, sizeof(numbersToSort), sizeof(numbersToSort[0]), comparison);
        for (i = 9; i >=0; --i)
            printf("%d\n", numbersToSort[i]);
    }
    
    
    int comparison ( const void *a, const void *b)
    {
        
        return (*(int*)a - *(int*)b) ;
    }
    int endProgram(void)
    {
        int d, c;
        printf("Try again? y/n: ");
        while ((c=getchar()) && c != '\n' && c != EOF) 
            d = c;
        if (d == 'y')
            return 1;
        else
            return 0;
    }

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    I haven't used qsort in a while so I may stand to be corrected but you could try...
    Code:
    int comparison ( const void *a, const void *b)
    {
        
        return (*((int*)a) - *((int*)b)) ;
    }
    or

    Code:
    int comparison ( const int *a, const int *b)
    {
        
        return (*a - *b) ;
    }

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    8
    Quote Originally Posted by CommonTater View Post
    I haven't used qsort in a while so I may stand to be corrected but you could try...
    Code:
    int comparison ( const void *a, const void *b)
    {
        
        return (*((int*)a) - *((int*)b)) ;
    }
    or

    Code:
    int comparison ( const int *a, const int *b)
    {
        
        return (*a - *b) ;
    }

    That did not solve the issue. I'm wondering if it could be somehow because of my conversion between a char array to an int array? After all, it seems that it works as long as I leave it with single digits. Of course, I have entered numbers in the hundreds and it sorts most of them but still screws up a few, so that may not be the problem either.

  6. #6
    Registered User
    Join Date
    May 2009
    Posts
    15
    Hey,

    You have two issues in your code.

    1. Getting 10 times bigger numbers: You need to properly end user input with '\0' in getNumber function because atoi will look to it to determine the end of the string. Otherwise if you input a big number first(more than one digits) and then small numbers, you get garbage in the rest of the cells(meaning if you input 100 the first time you probably get 100 times bigger values afterwards).

    2. Not sorting correctly: sizeof(numbersToSort) changed to 10 will work fine in your case. Evil sizeof...

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by vincent01910 View Post
    2. Not sorting correctly: sizeof(numbersToSort) changed to 10 will work fine in your case. Evil sizeof...
    Don't blame sizeof, there's nothing evil about it. It's role is pure and simple, and it serves it's purpose perfectly. I wouldn't have it any other way.

    The two main problems here are:
    1. Not using a constant for the number of values to enter, sort and display
    2. Not passing the size into the function, and then on into the second argument to qsort, so it knows how many items to sort.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    May 2009
    Posts
    15
    Sorry that I sounded like I was blaming sizeof. But I just meant sizeof may get you if you don't have profound understanding of it. . I like the idea of passing the argument though.
    Last edited by vincent01910; 09-18-2011 at 05:19 AM.

  9. #9
    Registered User
    Join Date
    Sep 2011
    Posts
    8
    Quote Originally Posted by vincent01910 View Post
    Hey,

    You have two issues in your code.

    1. Getting 10 times bigger numbers: You need to properly end user input with '\0' in getNumber function because atoi will look to it to determine the end of the string. Otherwise if you input a big number first(more than one digits) and then small numbers, you get garbage in the rest of the cells(meaning if you input 100 the first time you probably get 100 times bigger values afterwards).

    2. Not sorting correctly: sizeof(numbersToSort) changed to 10 will work fine in your case. Evil sizeof...
    Wow, thanks! Yes, I should have caught not adding the '\0'. I made the changed and now it works. I'm not understanding why sizeof didn't work though.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    That's because sizeof() only knows the size of an array in the same context (set of braces) in which it was created. Outside of that context the name of the array decays to a pointer to the array and the compiler no longer knows how big it is... sizeof() will then return the size of the pointer, not the size of the array.

  11. #11
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    To expand on Tater's answer, read through C-FAQ 6.21. Specifically, read through all the other links on that page so you can avoid other pitfalls with sizeof.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You never wanted anything like sizeof anyway. Even if the call to qsort was in main rather than in a separate function, then you'd be telling it to sort 4000 (or 2000) items instead of 10.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to use qsort
    By zcrself in forum C Programming
    Replies: 11
    Last Post: 12-29-2009, 09:22 PM
  2. Help here with qsort!
    By xxxrugby in forum C Programming
    Replies: 11
    Last Post: 02-09-2005, 08:52 AM
  3. qsort
    By linuxdude in forum C Programming
    Replies: 4
    Last Post: 03-08-2004, 01:29 PM
  4. qsort
    By chrismiceli in forum C Programming
    Replies: 13
    Last Post: 06-28-2003, 04:20 PM
  5. qsort please help. Thanks
    By Ann Lim in forum C Programming
    Replies: 8
    Last Post: 12-12-2002, 02:20 AM