- Suppose given an array of size n, with sorted values.
- In iteration i, a new random-generated value is given, and inserted into the end of the array.
- The array is then resorted, and discard the least value item.
- After iteration n, the retained array will contain the largest value items.
For example, in Java syntax, it will be something like:
List l = new ArrayList();
l.add(new Integer(2));
l.add(new Integer(3));
l.add(new Integer(6));
l.add(new Integer(9));
Random rand = new Random();
for (int i=0; i < n; i++) {
l.add(new Integer(rand.nextInt(1000)));
}
Collections.sort(l);
l.remove(0);
But it seems it's inefficient. Any better algorithm?