1

Hello guys i have a situation here am trying to sort out numbers in C language but i seem to struggle to put a sort function can you please help me with this following souce code that prints out number and supose to sort them but i cant...please help:

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

int main()
{
    int num1 = 8, num2 = 6, num3 = 2, num4 = 4, num5 = 1;
    printf("%d %d %d %d %d", num1, num2, num3, num4, num5);
    // qsort();  THIS IS WHAT I STRUGGLE WITH AT THE MOMENT
    return 0;
}  // THIS CODE PRINTS OUT NUMBERS BUT ARE NOT SORTED...SO I NEED TO SORT THEM PLEASE
   // YOUR HELP WILL BE MUCH APPRECIATED
   // I NEED TO KNOW HOW TO USE THE SORT(qsort) FUNCTION
Mike
  • 11
  • 1
  • 4
    Hello and welcome to StackOverflow! Did you read the documentation for `qsort`? – Daniel Walker Jun 08 '21 at 22:46
  • 2
    Biggest issue, `qsort` works on an array. Five named variables are not an array. – aschepler Jun 08 '21 at 22:47
  • Take the time and learn to write the `qsort()`, `compare()` function. It isn't difficult, the parameters are just pointers to elements of the array you are sorting. Once you take the time to make friends with `compare()`, using `qsort()` to sort any array of anything is dead-bang trivial. simply `qsort (array, nelements, elemsize, compare);` (done...) The answer for [Using qsort and strcmp prior to my sctrucs going into txt files](https://stackoverflow.com/a/51624493/3422102) expands on how to write a compare function. – David C. Rankin Jun 08 '21 at 22:54
  • Also [How to sort an array of structs nested in a array of structs C](https://stackoverflow.com/a/59077860/3422102) may help. – David C. Rankin Jun 08 '21 at 22:59
  • The duplicate for which this question was closed does not answer the question. It explains what `qsort()` is, but provides no explanation on how to use it. – David C. Rankin Jun 08 '21 at 23:38
  • 1
    Documentation of the `qsort()` function is available in many places. Googling just for the function name will turn up several appropriate hits at the top of the results. What is it about the documentation that you do not understand? – John Bollinger Jun 08 '21 at 23:43
  • @DavidC.Rankin: I disagree, several of the answers contain explanations of how to use the function, with complete examples. I won't vote to close again, but here's the link again anyway in case OP finds it helpful: https://stackoverflow.com/questions/1787996/c-library-function-to-perform-sort – Nate Eldredge Jun 09 '21 at 00:23

1 Answers1

3

qsort() does one thing and it does it exceptionally well, it sorts arrays, and does so very efficiently. As noted in the comments, before you can use qsort() you will need to collect your values in an array rather than separate variables. Once you have an array, using qsort() is trivial, your only responsibility using qsort is to write the compare() function.

New users of qsort() usually have their eyes roll back in their heads when they see the declaration for the function:

int compare (const void *a, const void *b) { ... }

It's actually quite simple. a and b are simply pointers to elements of the array to compare. Since qsort() can handle any type array, the parameter type are void pointers. If you have an array of int, a and b are just pointers int (e.g. int*). You simply need to write your compare function to cast a and b to int* and dereference to compare the int values with each other.

The return of compare() is either less than zero (a sorts before b), zero (a and b are equal) or greater than zero (b sorts before a). So a niave compare() can be as simple as:

int compare (const void *a, const void *b)
{
    int x = *(int *)a,
        y = *(int *)b;
    
    return x - y;
}

However, there is always a potential for x - y to overflow with a large negative x and large y or large x and large negative y. So you generally try and use the differnce between two comparisons to eliminate the potential for overflow, e.g.

int compare (const void *a, const void *b)
{
    int x = *(int *)a,
        y = *(int *)b;
    
    return (x > y) - (x < y);
}

Now if you take any value of a and b the return will either be -1, 0 or 1 providing the sort information for qsort() without chance of overflow.

A short example using your values could be written as:

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

int compare (const void *a, const void *b)
{
    int x = *(int *)a,
        y = *(int *)b;
    
    return (x > y) - (x < y);
}

void prn_arr (int *arr, size_t nmemb)
{
    for (size_t i = 0; i < nmemb; i++)
        printf (i ? ", %d" : "%d", arr[i]);
    
    putchar ('\n');
}

int main()
{
    int num[] = {8, 6, 2, 4, 1};
    size_t nmemb = sizeof num / sizeof *num;
    
    puts ("array before sort:\n");
    prn_arr (num, nmemb);
    
    qsort (num, nmemb, sizeof *num, compare);
    
    puts ("\narray after sort:\n");
    prn_arr (num, nmemb);
}

Example Use/Output

$ ./bin/qsortnum
array before sort:

8, 6, 2, 4, 1

array after sort:

1, 2, 4, 6, 8

Look things over and let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85