How does selection sort work with strings? I’ve done some searching and can’t seem to find a definitive answer. If I had 4 names [Rob, Adam, Tom, Thomas] – how would a selection sort, sort these? Would it just simply sort by the first letter? If so, would it sort like the following: [Adam, Rob, Thomas, Tom].
Thanks.
All sorting algorithms use some kind of comparison function to determine the order of elements. It’s generally independent of particular sorting algorithm you select.
Most languages try to guess the comparison function, depending of the type of sorted data. For example comparison on numbers simply checks which number is greater. Comparison function on strings uses dictionary order which compares consecutive letters. Some examples (GT – greater than, LT – less than):
Compare numbers:
letters:
strings (it compares letters internally, think how):
Sorting function uses this comparisons internally ([1,2,3] is a list of three numbers). You don’t know which sorting algorithm is used internally, but as long as the same comparison function is used, results shouldn’t vary:
You can even define your own comparison function, to sort by some more sophisticated criteria:
Sort list of numbers by count of prime divisors.
First custom comparison function:
Sort by length of strings
Comparison function: