Print the N longest lines in a file I have implemented the "Find the N longest lines in a file" problem from CodeEval quoted below. 

I got a full 100 score and 182ms execution time of their data set on the site so I consider the code to be working and effective. What I'm wondering is, is there something I can do to make this faster than it already is? Did I miss anything? Any other comments?




  Write a program which reads a file and prints to stdout the specified
  number of the longest lines that are sorted based on their length in
  descending order. Input sample:
  
  Your program should accept a path to a file as its first argument. The
  file contains multiple lines. The first line indicates the number of
  lines you should output, the other lines are of different length and
  are presented randomly. You may assume that the input file is
  formatted correctly and the number in the first line is a valid
  positive integer. 
  
  For Example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

  
  Output sample:
  
  Print out the longest lines limited by specified number and sorted by
  their length in descending order.
  
  For example:

San Francisco
Hello World



The code:



import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class NLongestLines {

    private final static Comparator&lt;String&gt; CMP = new Comparator&lt;String&gt;() {
        @Override
        public int compare(String arg0, String arg1) {
            return arg1.length() - arg0.length();
        }
    };

    private static void insertSorted(List&lt;String&gt; list, String string) {
        int max = list.size();
        int min = 0;
        int pivot = min + (max - min) / 2;

        // Binary search for insertion point.
        while (min &lt; max) {
            int c = CMP.compare(string, list.get(pivot));
            if (c &lt;= 0) {
                max = pivot;
            } else {
                min = pivot + 1;
            }
            pivot = min + (max - min) / 2;
        }

        list.add(min, string);
    }

    public static void main(String[] args) throws Exception {
        try (FileReader fr = new FileReader(args[0]); 
             BufferedReader reader = new BufferedReader(fr)) {
            List&lt;String&gt; longestLines = new ArrayList&lt;&gt;();

            String line = reader.readLine();
            {
                int numLongestLines = Integer.parseInt(line);
                while (numLongestLines &gt; 0 &amp;&amp; (line = reader.readLine()) != null) {
                    numLongestLines--;
                    line = line.trim();
                    insertSorted(longestLines, line);
                }
            }

            int shortestLongLength = findShortestLongLine(longestLines);
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.length() &gt; shortestLongLength) {
                    insertSorted(longestLines, line);
                    longestLines.remove(longestLines.size() - 1);
                    shortestLongLength = findShortestLongLine(longestLines);
                }
            }

            for (String longLine : longestLines) {
                System.out.println(longLine);
            }
        }
    }

    private static int findShortestLongLine(List&lt;String&gt; longestLines) {
        return longestLines.get(longestLines.size() - 1).length();
    }
}


Edit/Addendum:

I have implemented and benchmarked the proposed solutions by Simon Forsberg (TreeSet) and RolfL (LinkedList). 

The results can be seen here. The executive summary is that the original algorithm is significantly faster than the proposals in just about all test cases.

The source used for testing can be found here. Needs µbench from here.
the other lines are of different length and are presented randomly


I understand this as that all lines have different length. As such, I would make a different choice of data structure. Namely, a TreeSet&lt;String&gt;.

A TreeSet can be constructed with a Comparator, so I would use your existing comparator as the constructor for this TreeSet. Then I would use the descendingIterator() method to iterate x times over your elements in descending order.

Note: Even if there would be lines of the same length, you could still use a TreeSet but then you'd need to compare on both the length and the String itself, to avoid ignoring the insertion of an element that has the same length as a previous existing element. (If elements can be exactly identical, then TreeSet will not work well)

This will allow us to get rid of your insertSorted method and get rid of the potentially slow ArrayList.add(index, object) call which is \$O(n - index)\$