# Programming-Idioms

This language bar is your friend. Select your favorite languages!

# Idiom #290 Sort sublist

Sort the part of the list items from index i (included) to index j (excluded), in place, using the comparator c.

Elements before i and, j and after, must remain unchanged.

``items[i..j].sort_by(c);``
``items.setRange(i, j, items.sublist(i, j)..sort(c));``
``````sub := items[i:j]
sort.Slice(sub, func(a, b int) bool {
return c(sub[a], sub[b])
})``````
``import "golang.org/x/exp/slices"``
``slices.SortFunc(items[i:j], c)``
``````import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;``````
``````Comparator<T> c = new Comparator<T>()
{
@Override
public int compare(T o1, T o2)
{
if(o1 > o2) {
return 1;
} else if(o1 == o2) {
return 0;
} else {
return -1;
}
}
};
Collections.sort(items.subList(i, j), c);``````
``use feature 'say';``
``````@items = qw(0 1 2 3 a b c d e 9 10 11);
(\$i,\$j) = (4,8);
\$c = sub { \$b cmp \$a }; # sort alpha descending

say '# ', join ' ', @items;

@items[\$i..\$j] = sort \$c @items[\$i..\$j];

say '# ', join ' ', @items;

# output:
# 0 1 2 3 a b c d e 9 10 11
# 0 1 2 3 e d c b a 9 10 11
``````
``import functools``
``items[i:j] = sorted(items[i:j], key=functools.cmp_to_key(c))``
``items[i:j] = sorted(items[i:j], key=c)``

programming-idioms.org