Example & explanation:
Let user inputs 5 names as following:
rahul
virat
vijay
bumrah
rahane
Alphabetical sorting means to sort names according to alphabet order starting from the rightmost character. (Rightmost character->'r' for 'rahul').
That means, in the 'rahul' precedes 'vijay' in alphabetical order since rightmost character of 'rahul' is 'r' where as rightmost character of 'vijay' is 'v' & 'r' precedes 'v' in alphabetical order.
The next concern is what about 'rahul' & 'rahane' since both of them has same rightmost character. In such cases compare corresponding elements from right to left direction.
Thus 'rahane' precedes 'rahul' since 'a' precedes 'u' in alphabetical order. (Both have 'rah' part common).
One more thing is 'abdul' will precedes 'abdulla' as both have 'abdul' as common part & 'abdul' has nothing left where 'abdulla' has.
So using the above facts the names will appear after sorting:
bumrah
rahane
rahul
vijay
virat
Algorithm:
1. Constructing list of names
Declare a vector of strings & take each string &insert to the vector.
2. Sorting in alphabetical order
We can sort the vector using our own comparator function to sort the strings in alphabetical order.
Our comparator function is defined as:
Now to sort the vector of string we use this comparator function while using STL sort function.
C++ implementation for Sorting Names in an Alphabetical Order
Output