Bifalgorithm post · Computer science one · Comparators

How does a Comparator determine the order of two elements?

How does a Comparator determine the order of two elements? (Computer science one · Comparators) — "A generic sorting algorithm such as Quick Sort specifies how…

Ideas in this flowchart

  • A Comparator defines the ordering needed by a generic Quick Sort algorithm.
  • Quick Sort specifies how to sort elements, but not how the elements are ordered.
  • Quick Sort must determine whether two elements are in order, out of order, or equivalent.
  • The elements may be numbers, strings, or user-defined objects.
  • In Java, a Comparator object determines the proper ordering.
  • Comparator<T> is parameterized to operate on any type T.
  • It implements the method public int compare(T a, T b), whose arguments have type T.
  • The sign of compare's return value expresses the ordering relationship.
  • A negative value means that a comes before b.
  • Zero means that a and b are equal.
  • A positive value means that a comes after b.
  • The magnitude of the returned value is not guaranteed; it need not be -1 or +1.
Feed/

How does a Comparator determine the order of two elements?

No cover

Channel

Computer science one

1 page

"A generic sorting algorithm such as Quick Sort specifies how to sort elements, but it does not specify how those elements are ordered. Quick Sort needs to know when two elements, a and b, are in order, out of order, or equivalent so it can decide which partition each element belongs in. The elements could be numbers, strings, or user-defined objects. In Java, a Comparator object determines the proper order by implementing the method public int compare(T a, T b). A Comparator<T> is parameterized to operate on any type T, and the method takes two instances whose type matches T. The method returns a negative value if a comes before b, zero if a and b are equal, and a positive value if a comes after b. There is no guarantee about the magnitude of the returned value; it does not necessarily return -1 or +1."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.