Polyglot CheatSheet - Sort

Updated: 2021-11-19

C++

vector<int> vals = {-1, -2, -3, 1, 2, 3, 0};
int p = 2;

sort(vals.begin(),
     vals.end(),
     [p](int a, int b) {
        return pow(a, p) < pow(b, p);
        });

Java 8+

list.stream().sorted()

Or

list.sort((Foo o1, Foo o2) -> o1.getBar() - o2.getBar());

Reverse

list.stream().sorted(Comparator.reverseOrder())

Use Collections.sort()

Collections.sort(vals, (a, b) ->
        Integer.compare(Math.pow(a, p), Math.pow(b, p)));

Javascript

Sort array

arr.sort((a,b) => { return parseFloat(a.data) - parseFloat(b.data) } );

arr.sort((a,b) => { return a.str.localeCompare(b.str) } );

arr.sort((a,b) => { return a.str.toUpperCase().localeCompare(b.str.toUpperCase() } );

Sort object

const sortedObj = Object.keys(obj)
  .sort()
  .reverse()
  .reduce((newObj, k) => {
    newObj[k] = obj[k];
    return newObj;
  }, {});

Python

By default, sort, sorted, heapq can sort tuples: the first element first and on the second element second. Can specify key to override default. cmp is deprecated in Python 3

sorted_data = sorted(data, key=lambda x: x['key'])

or sorts in place

data.sort(key=lambda x: x['key'])

Sort on multiple keys, suppose x is a tuple (int, int, boolean)

data.sort(key=lambda x: (x[0], not x[2]))

Sort dict

import operator
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)

Rust

let mut vals = [-1, -2, -3, 1, 2, 3, 0];
let p = 2;

vals.sort_by(|a :&isize, b :&isize|
                a.pow(p).cmp(&b.pow(p)));