Added key index counting method for sorting