Logo

Programming-Idioms

  • Kotlin
  • C++
  • Java
  • Obj-c

Idiom #100 Sort by a comparator

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

@import Foundation;
[items sortUsingComparator:c];

Sorts in-place; for creation of a new sorted array leaving the receiver unchanged there's sortedArrayUsingComparator:
items.sortWith(c)
#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.

import java.util.Arrays;
import java.util.Comparator;
Arrays.sort(items, c);

items is an array of type Item[].
c implements Comparator<Item>.
import java.util.Collections;
import java.util.Comparator;
Collections.sort(items, c);

items is a List<Item>.
c implements Comparator<Item>.
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...