Logo

Programming-Idioms

  • Smalltalk
  • C#

Idiom #100 Sort by a comparator

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

Array.Sort(items, c);

items is an array of type Item[].
c implements IComparer<Item>
using System.Collections.Generic;
items.Sort(c);

items is a List<Item>
c is an implementation of IComparer<Item>
using System;
using System.Linq;
var orderdEnumerable = x.OrderBy(y => y, c);
| c |
c := [ :a :b | a size <= b size ].  " example c for strings "
#('a' 'aaa' 'a' 'aaaa') asSortedCollection: c.
" => SortedCollection('a' 'a' 'aaa' 'aaaa') "
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...