Fast final version with Arrays.sort used