Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Can someone please explain how these codes work?  RSS feed

 
beu curt
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been reading this for awhile now, but I just can't figure the flow and idea of this code.



Any explanation would be very helpful, thank you
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What it appears to be doing is this:

- person is an array of two-element arrays. The inner array is used to contain a name/telephone number pair.

- The nest loops sort this into alphabetical order based on the name. It's using what's known as a "bubble sort" (you'll find lots of references if you search for that), which is probably the simplest sorting algorithm to code. It's based on swapping adjacent values if they're in the wrong order, until they're all in the right order.

If this is a real application, though, instead of just a demonstration it's a bit clumsy. I'd suggest a much better solution would be:

- Create a class to hold the names and phone numbers together, so you just have an array of these objects.
- Create a Comparator that can be used to sort this by name.
- Use Arrays.sort for the sorting (using the Comparator).

Or even (whether this is suitable depends on what other functionality you need) put the names/telephone numbers in a TreeMap (with the names as the key) - which will automatically sort it for you!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!