Logo

Programming-Idioms

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.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
(->> (map vector a b)
     (sort-by first)
     (apply (partial mapv vector)))
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,
})
import Data.List
let (outA,outB) = unzip $ sort $ zip a b
uses classes;
type
  TPairedList = class(TStringList)
  private
    FBuddy: TStrings;
  protected
    procedure ExchangeItems(Id1, Id2: Integer); override;
  public
    procedure Sort(Buddy: TStrings); overload;
  end;

procedure TPairedList.ExchangeItems(Id1, Id2: Integer);
begin
  inherited Exchange(Id1, Id2);
  if Assigned(FBuddy) then
    FBuddy.Exchange(Id1, Id2);
end;

procedure TPairedList.Sort(Buddy: TStrings);
begin
  FBuddy := Buddy;
  Sort;
end;

begin
  ...
  a.sort(b);
end.
use List::Util qw(zip pairmap unpairs);
@keys = qw(x y a f e n);
@vals = qw(1 2 3 4 5 6);

pairmap { push @new_keys, $a; push @new_vals, $b }
    unpairs 
        sort { $a->[0] cmp $b->[0] } 
            zip \@keys, \@vals;
import operator
temp = list(zip(a, b))
temp.sort(key=operator.itemgetter(0))
a, b = zip(*work)
a, b = a.zip(b).sort.transpose
let mut tmp: Vec<_> = a.iter().zip(b).collect();
tmp.as_mut_slice().sort_by_key(|(&x, _y)| x);
let (aa, bb): (Vec<i32>, Vec<i32>) = tmp.into_iter().unzip();