Input : {5, 13, 6, 5, 13, 7, 8, 6, 5}
Output : {5, 5, 5, 13, 13, 6, 6, 7, 8}
The question is to arrange the numbers in the array in
Sort the array, and in your sort function for x, y: sort by count(x) vs. count(y). If they are the same, sort by index(x) vs. index(y)
In python:
input = [5, 13, 6, 5, 13, 7, 8, 6, 5] orig = list(input) def cmp(x, y): if (orig.count(y) - orig.count(x) != 0): return orig.count(y) - orig.count(x) return orig.index(x) - orig.index(y) input.sort(cmp) print input
To make it more efficient, precalculate counts and indexes before sorting the array.