Logo

Programming-Idioms

  • C++
  • C#

Idiom #100 Sort by a comparator

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

using System;
using System.Linq;
var orderdEnumerable = x.OrderBy(y => y, c);
using System.Collections.Generic;
items.Sort(c);

items is a List<Item>
c is an implementation of IComparer<Item>
Array.Sort(items, c);

items is an array of type Item[].
c implements IComparer<Item>
#include <algorithm>
std::ranges::sort(items, c);

Requires C++20.
#include <algorithm>
#include <vector>
#include <cassert>
struct is_less {
    bool operator () (int a, int b){
        return a < b;
    }
};

int main(){
    std::vector<int> items = {1337, 666, -666, 0, 0, 666, -666};
    std::sort(items.begin(), items.end(), is_less());

    std::vector<int> expected = {-666, -666, 0, 0, 666, 666, 1337};
    assert(items.size() == expected.size());
    for (size_t i = 0; i < items.size(); i++){
        assert(items[i] == expected[i]);
    }
    return 0;
}

c is a bad name for a comparator because it is not descriptive. is_less is a better name.

The initializer list for items requires the compiler parameter -std=c++11

std::sort might not be stable. If you want a stable sorting algorithm, use std::stable_sort instead.

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