Internal working of timsort and compareTo() method in Comparable interface

62 views Asked by At

I have been looking at different articles on internet and everyone mentions that compareTo() method would follow natural ordering by default. Let's taken an example.

class Car implements Comparable<Car> {
  int id
  Car(int id){
    this.id = id;
  }

  public int compareTo(Car car){
    return this.id - car.id;    //ascending
  }

}

It was mentioned that compareTo only specifies if the object being compared with the current object is greater, smaller or equal and it really does n't control the swap of the elements in sorting. if so, why does the array gets sorted when we just reverse the return type like

return car.id - this.id     //descending

Here, the main question is if the compareTo purpose is only to find which object is smaller or greater How does the timsort understands if the sorting should be in ascending or descending order. We have n't specified it anywhere. please explain with any example so it would help everyone. Thanks in advance

0

There are 0 answers