Logo

Programming-Idioms

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

Idiom #240 Sort 2 lists together

Lists a and b have the same length. Apply the same permutation to a and b to have them sorted based on the values of a.

(->> (map vector a b)
     (sort-by first)
     (apply (partial mapv vector)))

this returns [a b]
the last line is from the 2d- transpose solution
import "sort"
type sorter struct {
	k []K
	t []T
}

func (s *sorter) Len() int {
	return len(s.k)
}

func (s *sorter) Swap(i, j int) {
	s.k[i], s.k[j] = s.k[j], s.k[i]
	s.t[i], s.t[j] = s.t[j], s.t[i]
}

func (s *sorter) Less(i, j int) bool {
	return s.k[i] < s.k[j]
}

sort.Sort(&sorter{
	k: a,
	t: b,
})

The custom type sorter implements the 3 methods of sort.Interface.
Swap affects the order of 2 slices at once.

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