Logo

Programming-Idioms

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

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.

import static java.util.Collections.swap;
import java.util.List;
record QuickSort<T extends Comparable<T>>(List<T> a, List<?> b) {
    void sort(int x, int y) {
        if (x >= y || x < 0) return;
        int p = f(x, y);
        sort(x, p - 1);
        sort(p + 1, y);
    }
    int f(int x, int y) {
        T t = a.get(y);
        int i, j = i = x;
        do if (a.get(j).compareTo(t) < 1) {
            swap(a, i, j);
            swap(b, i++, j);
        } while (++j < y);
        swap(a, i, y);
        swap(b, i, y);
        return i;
    }
}
(->> (map vector a b)
     (sort-by first)
     (apply (partial mapv vector)))

this returns [a b]
the last line is from the 2d- transpose solution

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