Excluding sorting, this is O(n) which should be much faster and much simpler and easier to understand.
Attach a file by drag & drop or click to upload