Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does compareTo and compare work?

Tags:

java

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

like image 956
vijay Avatar asked Sep 12 '12 10:09

vijay


People also ask

What is the difference between compareTo and compare?

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.

How do you use compareTo comparable?

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.

What is difference between == equals () and compareTo () method?

The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.


2 Answers

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.

like image 138
user207421 Avatar answered Oct 14 '22 10:10

user207421


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 :)

like image 37
amit Avatar answered Oct 14 '22 10:10

amit