Logo

Programming-Idioms

  • Elixir
  • C

Idiom #100 Sort by a comparator

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

#include <stdlib.h>

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;
}

The comparison is often written as "return x - y;" instead which is broken due to possible integer over/underflow.
Enum.sort(items, c)
with Ada.Containers.Vectors;
use Ada.Containers;
type Integer_Comparator is not null access function (Left, Right : Integer) return Boolean;
      
package Integer_Vectors is new Vectors (Positive, Integer);
use Integer_Vectors;
      
procedure Sort_Using_Comparator (V : in out Vector; C : Integer_Comparator) is
   package Vector_Sorting is new Generic_Sorting (C.all);
   use Vector_Sorting;
         
begin
   Sort (V);
end Sort_Using_Comparator;

New implementation...
< >
programming-idioms.org