Sorting Characters By Frequency in C++

Photo by Dimitry B on Unsplash

Sorting Characters By Frequency in C++

Overview

In this task breakdown, we will be looking at sorting characters in strings in order of magnitude of appearance. Most of the time, you have seen the task that involves sorting characters alphabetically in a string or an array, in this particular task we will be sorted based on the number of occurrences of a character. This might not have much real-life application but sure it is a good way of practicing some programming concepts. Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Thought Process

To explain my thought process in the coding exercise, I will use a sample string Saamueeel, suppose I am to sort this based on the requirement described above, one way of approaching this is to first identify all unique elements in this string and then iterate over all the unique elements and count the number of each of their occurrences in the original string, after this, we can now sort by the highest counts. C++ Standard Template Library comes with different classes and libraries to help implement this, the count, sort, priority_queue, and unordered_map were used.

priority_queue<pair<int, char>>prg;

The code snippet shown above is a sample call of priority_queue along with pair to save the number of counts and the character in the sample string. After the sample string Saamueeel has gone through this process, it returns a sorted string eeeaamulS.

Conclusion

There are lots of sample problems that help practice coding skills sorting by character frequency is another one. Depending on how you can think about it, the task above can be implemented in different ways even without using specialized data types.