Logo

Programming-Idioms

History of Idiom 100 > diff from v17 to v18

Edit summary for version 18 by :
[C] code wrong

Version 17

2016-02-18, 18:53:27

Version 18

2016-02-18, 19:02:40

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Imports
#include <stdlib.h>
Imports
#include <stdlib.h>
Code
int c(const void *a,const void *b)
{
	const int *ap=(const int *)a;
	const int *bp=(const int *)b;
	return *a-*b;
}

int main(void)
{
	int arr[]={1,6,3,7,2};
	qsort(arr,sizeof(arr)/sizeof(*arr),sizeof(*arr),c);

	return 0;
}
Code

int c(const void *a,const void *b)
{
	int x = *(const int *)a;
	int y = *(const int *)b;

	if (x < y) return -1;
	if (x > y) return +1;
	return 0;
}

int main(void)
{
	int arr[]={1,6,3,7,2};
	qsort(arr,sizeof(arr)/sizeof(*arr),sizeof(*arr),c);

	return 0;
}
Comments bubble
The comparison is often written as "return x - y;" instead which is broken due to possible integer over/underflow.