简体   繁体   中英

bubble sort a string array by length of string

I am wondering how to use Bubble Sorting to sort a list of names ( like: Bob, Robert, Dave, Kelly) in increasing order of the length of their names. I know how to use bubble sort to sort their names alphabetically, but just want to know how to sort by their name length. Would I have to convert to names to integers and then sort the integers by amount? Thanks,

When comparing two String values by length instead of alphabetically, use the String.length() method instead of using String.compareTo()

ie: change your

if(a.compareTo(b) < 0)

to

if(a.length() < b.length())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM