I know that compare and compareTo
returns an int
value.
For example:
Returns 0 if a equal b -1 if a < b +1 if a > b
sort
method makes a call to either compareTo
or compare()
methods. But how does sort
method arranges the list
when compare or compareTo
returns a int
value. What is background scenario running after a compare
or compareTo
returns an int value to sort?how does sort
method makes use of int values(-1
or 0
or 1
) returned to it from compare
and compareTo
What are the differences between compareTo() and compare() methods in Java? The Comparable interface provides a compareTo() method for the ordering of objects. This ordering is called the class's natural ordering and the compareTo() method is called its natural comparison method.
The compareTo method required by the Comparable interface receives as its parameter the object to which the "this" object is compared. If the "this" object comes before the object received as a parameter in terms of sorting order, the method should return a negative number.
The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.
If the two elements (a,b) being compared are already in the right order, compare(a, b)
and a.compareTo(b)
both return a value that is <= 0
, so nothing has to happen.
If they aren't in the right order, the return value is > 0
, indicating that they must be interchanged.
General case sorting algorithms are based on comparisons. If you compare between a
and b
- there are exactly 3 possibilities: a == b
, a > b
, a < b
.
The compare()
or compareTo()
method provides exactly this information.
Now, to use this information we have designed numerous sorting algorithms, starting with naive bubble sort, and some are more advances such as quick sort. Each providing a bit different approach to the sorting problem.
Java chose the TimSort algorithm for its sorting implementation.
As an exercise, you can design your own1 sorting algorithm. Can you find the maximum element of an array using the compare()
method? when you found it where should it be? what should you do next?
(1) Well, think of it by yourself, but it already exists, actually :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With