0

I have to sort the values of a hash map in ascending order using the heap sort algorithm, and then return the corresponding sorted list of keys. My approach was to simply perform the heapsort algorithm on the values only, and then using for loops, return the corresponding list of keys, like so:

ArrayList<Double> valueList = new ArrayList<Double>();

for(Map.Entry<String, Double> entry : map.entrySet()) {
    double value = entry.getValue();
    valueList.add(value);
}

int n = valueList.size();
for (int i = n/2 - 1; i >= 0; i--) {
    heapify(valueList, n, i);
}

for (int i = n - 1; i >= 0; i--) {
    double temp = valueList.get(0);
    valueList.set(0, valueList.get(i));
    valueList.set(i, temp);
    heapify(valueList, i, 0);
}
ArrayList<String> keyList = new ArrayList<String>();
for (int i = 0; i < valueList.size(); i++) {
    for(Map.Entry<String, Double> entry : map.entrySet()) {
        if(entry.getValue() == valueList.get(i)) {
            keyList.add(entry.getKey());
        }
    }
}
return keyList;

However when I debug, or try to run the JUNIT test cases, it says that my array list of keys is empty. Is this approach not correct? Am I going to have to sort the values and keys simultaneously?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

0 Answers0