Sorting datas in C.

A sample about the standard qsort function.

qsort

See version :

Pas de dépendances

Download :

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

int compint(const void* a,const void* b)
{
    int* pa=(int*)a;
    int* pb=(int*)b;
    int ea=*pa;
    int eb=*pb;
    return ea-eb;
}

int main()
{
    int nombres[5];
    int i;
    printf("Entrez 5 nombres\n");
    for(i=0;i<5;i++)
        scanf("%d",&nombres[i]);
    qsort(&(nombres[0]),5,sizeof(int),compint);
    printf("tri ok.\n");
    for(i=0;i<5;i++)
        printf("%d\n",nombres[i]);
    return 0;
}




Explanations

	qsort function can sort any contiguous array.

	qsort take 4 parameters.
	The first one is the adress a the array to sort.
	The second is the number of elements
	The third is the size of one element.

	The fourth is a function. This function will describe "how to know, for 2 given elements, which one is greater ?"

	This function has this signature :

	int compint(const void* a,const void* b)

	This is pure pointers : void*

	You have to cast these pointers into a pointer of your elements, then telling how to know whish is better.
	Let see the example : (compint mean "compare int")

	int compint(const void* a,const void* b)
	{
	int* pa=(int*)a;
	int* pb=(int*)b;
	int ea=*pa;
	int eb=*pb;
	return ea-eb;
	}

	First, I cast the pointers into int*, because my array is an array of int.
	Then I retrieve the int into ea and eb.
	Finally, how to know which int is greater ? Just make a substraction : if 0, it's equal, if result<0, then a<b, if result>0, then a>b.