Logo

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 after j must remain unchanged.

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)
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)
items[i..j].sort_by(c);

New implementation...
< >
programming-idioms.org