Panda Noir

JavaScript の限界を究めるブログでした。最近はいろんな分野を幅広めに書いてます。

安定ソートはフィルタリングである

const arr = [5, 2, 7, 8, 1, 4];

arr.sort((a, b) => (b % 2) - (a % 2));

console.log(arr) // [5, 7, 1, 2, 8, 4]

実質的にpartitionになっている。あたりまえ体操。

でも、単にpartitionしたいだけならO(N)でできるのであんまり意味はない。

function partition<T>(
  arr: T[],
  cond: (x: T) => boolean,
): [T[], T[]] {
  const t: T[] = [], f: T[] = [];
  for (const x of arr) (cond(x) ? t : f).push(x);
  return [t, f];
}
partition(arr, a => a % 2 === 1); // [[ 5, 7, 1 ], [ 2, 8, 4 ]]

ソートと同時にpartitionしたいときはたまにあるので、覚えておくと時々役に立つかもしれない