Skip to content

Instantly share code, notes, and snippets.

@raphaelrk
Last active May 4, 2017 16:41
Show Gist options
  • Save raphaelrk/28e8ae0b46c9b87e3346 to your computer and use it in GitHub Desktop.
Save raphaelrk/28e8ae0b46c9b87e3346 to your computer and use it in GitHub Desktop.
sorting based on frequency of elements in descending order
/*** java pseudocode ***/
/* a NumTuple holds a number and the frequency of its occurences */
class NumTuple {
int num, freq = 1;
public numTuple(num) { this.num = num; }
}
ArrayList frequencySort(int[] array) {
result = ArrayList<NumTuple>;
map = HashMap<Integer, NumTuple>;
for(element in array) {
if(map.contains(element)) { // if the number's been read before
// modify tuple frequency
map.value(element).freq++;
}
else {
// create a new tuple
tuple = new NumTuple(element);
// add the tuple to the map
map.push(element, tuple);
//add the tuple to the array
result.append(tuple);
}
}
// proceed to sort the arrayList of numTumples by their frequencies
cs101sort(result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment