Topology { static int[] sort(int[] vs, int[] rank) { int[] ws = Arrays.copyOf(vs, vs.length); for (int i = 0, j = i; i < vs.length - 1; j = ++i) { int v = ws[i + 1]; while (rank[v] < rank[ws[j]]) { ws[j + 1] = ws[j]; if (--j < 0) break; } ws[j + 1] = v; } return ws; }    }
@Test public void sort() { int[] org = new int[]{1, 2, 3, 4}; assertThat(Topology.sort(org, new int[]{0, 1, 2, 3, 4}), is(not(sameInstance(org)))); assertThat(Topology.sort(org, new int[]{0, 1, 2, 3, 4}), is(new int[]{1, 2, 3, 4})); assertThat(Topology.sort(org, new int[]{0, 2, 1, 3, 4}), is(new int[]{2, 1, 3, 4})); assertThat(Topology.sort(org, new int[]{0, 2, 1, 7, 4}), is(new int[]{2, 1, 4, 3})); }