2

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.

9
  • 1
    How would it work without a compare function? Via magic? Commented Nov 18, 2012 at 23:49
  • 2
    @RobertKilar: Is there a reason you're trying to teach them C if the concepts are too hard for them to grasp? Commented Nov 18, 2012 at 23:52
  • 2
    Well if you claim that the other person won't be able to understand how to pass a parameter to qsort, then you are out of luck and will have to implement the sort yourself. This page claims to have the simplest sorting algorithm in the world -- and it is in C! Commented Nov 18, 2012 at 23:52
  • 3
    Why not build up to it. I mean qsort and passing functions is not where one would normally start when introducing C. Start with what is easy in C, not what is easy in Java. Commented Nov 19, 2012 at 0:02
  • 1
    Why don't you simply write the function in a header and tell them to include it? It's not hard to understand, it's just like the #include <stdio.h> needed to call printf. Compromises and "magic" are needed to learn a language, everyone has learned to print "hello world" with printf before knowing what is a function... Commented Nov 19, 2012 at 0:08

4 Answers 4

7

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) );
Sign up to request clarification or add additional context in comments.

7 Comments

I know how it can be done, but I know that this person at this level will not understand it.
You should show how to use the compare_int in the context of qsort.
There is no other magic function in C. You are free instead to teach your student to write insertion sort, merge sort, or quick sort themselves if you think that's easier. Or you could combine the lesson with an explanation of pointers, arrays and functions - all critically important if you want to go anywhere with C.
@RobertKilar maybe this sounds a bit harsh but as C is pretty low-level there's not really a way round this type of concepts, so if they're too hard for your student C is maybe not the next language (s)he should learn.
I have edited my post to suggest that a lesson on sorting in C can actually be quite enriching - it allows you to cover several topics with a small amount of code, and provide insight into what makes C tick.
|
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 :-)

Comments

0

If you're just doing this for teaching purposes, why don't you just write your own easy-to-use sort() based on qsort()? There isn't a standard function that is as simple as you're looking for, so implementing your own is the best option.

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

void sort(int *arr, size_t len) {
    qsort(arr, len, sizeof(int), compare);
}

2 Comments

Using minus in the compare function is a bit of a hack because overflow breaks it. For example, if you were to compare -2 with INT_MAX, the result would be positive.
@paddy Fair enough; it is the simplest implementation, and for demonstration purposes on small integers it will work fine, but you're right, doing a comparison is probably better.
0

**If you are reading this you will get an idea about sorting **

package com.alindal.sort;
import java.util.Scanner;

public class Sort {

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        int[] numers;
        System.out.println("Enter the number of elements: ");

        Scanner n=new Scanner(System.in);
        int x=n.nextInt();
        int[] srt=new int[10];
        for(int i=0;i<x;i++)
        {
            srt[i]=n.nextInt();
            }


        System.out.println("The sorted numbers :");
        for(int i=0;i<x-1;i++)
        {
            for(int j=i+1;j<x;j++)
            {

                if(srt[i]>srt[j])
                {
                    int temp=srt[i];
                    srt[i]=srt[j];
                    srt[j]=temp;

                }
                else{
                    srt[i]=srt[i];
                srt[j]=srt[j];
            }

        }

        for(i=0;i<x;i++)
        {
        System.out.println(srt[i]);
        }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.