# compareTo() and sort()

geet kaur

Ranch Hand

Posts: 79

Campbell Ritchie

Sheriff

Posts: 50679

83

posted 8 years ago

For compareTo() go to the API documentation for the Comparable<T> interface, and it tells you what you have to implement.

For sorting, many methods use a version of recursive merge sort with omission of already-sorted subsets. Merge sort has the advantage of being stable (it doesn't swap round two objects with the same value) whereas the faster quicksort might swap them round. That means you can sort on name, then age, and the names will remain in order for the same age. For primitives, it doesn't matter whether the sorting is "stable" so they use quicksort.

You can Google for merge sort or sorting algorithms; this is a nice link with animations!

For sorting, many methods use a version of recursive merge sort with omission of already-sorted subsets. Merge sort has the advantage of being stable (it doesn't swap round two objects with the same value) whereas the faster quicksort might swap them round. That means you can sort on name, then age, and the names will remain in order for the same age. For primitives, it doesn't matter whether the sorting is "stable" so they use quicksort.

You can Google for merge sort or sorting algorithms; this is a nice link with animations!

geet kaur

Ranch Hand

Posts: 79

Rusty Shackleford

Ranch Hand

Posts: 490

posted 8 years ago

Yes.

The best way to learn about sorting is to write your own search routines. That way you will get first hand knowledge instead of trying to figure out what is going on in a black box.

Merge sort and quick sort are fairly complicated algorithms. Start simple, bubble sort is a quick and easy algorithm to implement. It should be very clear how compareTo gets used. It will also start you down the important path of time complexity.

http://en.wikipedia.org/wiki/Bubble_sort

[ September 13, 2008: Message edited by: Rusty Shackleford ]

The best way to learn about sorting is to write your own search routines. That way you will get first hand knowledge instead of trying to figure out what is going on in a black box.

Merge sort and quick sort are fairly complicated algorithms. Start simple, bubble sort is a quick and easy algorithm to implement. It should be very clear how compareTo gets used. It will also start you down the important path of time complexity.

http://en.wikipedia.org/wiki/Bubble_sort

[ September 13, 2008: Message edited by: Rusty Shackleford ]

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra

Campbell Ritchie

Sheriff

Posts: 50679

83