Easiest to use int array sorting function in C

15,389

Solution 1

So... implement the function and be done with it...

int compare_int( const void* a, const void* b )
{
    if( *(int*)a == *(int*)b ) return 0;
    return *(int*)a < *(int*)b ? -1 : 1;
}

const size_t num_elem = 10;
int elements[num_elem] = { 3, 6, 1, 9, 8, 2, 0, 5, 7, 4 };
qsort( elements, num_elem, sizeof(int), compare_int );

Now your lesson about sorting becomes "how does this work"?

You start by explaining memory layout and arrays. You can't do much in C until you know this anyway.

Then you explain what a void pointer is and why the qsort function needs to know:

  1. The start address of your array
  2. The number of elements
  3. The size of each element
  4. How to compare the elements

That leads naturally to the comparison function itself... How to cast and dereference types.

Finally, if they are grasping the concepts well, you could point out that the fourth parameter to qsort isn't a special case. You can say it's perfectly okay to have a pointer to a function and pass that as a parameter to another function. It's all about the getting the type of the pointer correct, then the compiler sorts the rest out for you.

int (*comparator)(const void*, const void*) = compare_int;
int a = 1, b = 2;
printf( "comparator(%d, %d) = %d\n", a, b, comparator(&a, &b) );

Solution 2

The easiest way, at my first C programming course I've written this without looking for any algorithm online:

for(int i=0; i<N;i++)
{
    for(int j=0;j<N-1;j++)
    {
        if(array[j]<array[j+1])
        {
            int temp=array[j];
            array[j]=array[j+1];
            array[j+1]=temp;
        }
    }
}

I knew that it could be made in less that N*(N-1) iterations, but I didn't know how to calculate the exact number of iterations, so to be sure to sort all elements I made it this way.
If you want you can reduce the number of iterations by knowing that at every iteration one element gets sorted, so do the second loop can go from 0 to N-i-1.But I was too lazy to calculate this number and for the professor was ok :-)

Share:
15,389
Yoda
Author by

Yoda

If you have a question about Bonjour in .NET and AXIS SDK I am the guy. I HATE telerik.

Updated on June 27, 2022

Comments

  • Yoda
    Yoda almost 2 years

    I am looking for easiest to use array sorting function in C. I am going to teach somebody little bit of C(actually these are common basics to every language). Is there any function for int arrays like Java's

    Arrays.sort(arr);
    

    I have seen qsort, but as I saw it needs additional compare function.