What is the temporal complexity of sorting a list of objects with two properties?


Suppose I have a class: `

public class Interval {
    int start;
    int end;
    Interval() { start = 0; end = 0; }
    Interval(int s, int e) { start = s; end = e; }


I would like to sort a list of intervals with Collections.sort() like this:

Collections.sort(intervals, new Comparator<Interval>(){
    public int compare(Interval o1, Interval o2) {
        if (o1.start == o2.start) {
            return o1.end - o2.end;
        else {
            return o1.start - o2.start;

I know that sorting an array with the built-in sorting function takes O(nlogn) time, and the question is if I am sorting a list of objects with two properties, what is the time complexity of sorting this list? Thanks!!

@PaulMcKenzie's brief answer in comments is on the right track, but the real answer to your question is more subtle.

Many people do what you've done and confuse time with other measures of efficiency. What's correct in nearly all cases when someone says a "sort is O(n log n)" is that the number of comparisons is O(n log n).

I'm not trying to be pedantic. Sloppy analysis can make big problems in practice. You can't claim that any sort runs in O(n log n) time without a raft of additional statements about the data and the machine where the algorithm is running. Theoretical papers do this by stating a standard machine model used for their analysis. The model states the time required for low level operations of algorithms - memory access, arithmetic, and comparisons, for example.

In your case, each comparison requires a constant number for comparisons, so as long as comparison itself is constant time -- true in practice for fixed-width integers -- you're in good shape.

However, something as simple as string sorting changes this picture. String comparison itself has a variable cost. It depends on string length! So sorting strings with a "good" sorting algorithm is O(nk log n) where k is the length of strings.

Ditto if you're sorting variable-length numbers (java BigIntegers for example).

Sorting is also sensitive to copy costs. Even if you can compare objects in constant time, sort time is going to depend how big they are. Algorithms differ in how many times objects need to be moved in memory. Some accept more comparisons to prevent unnecessary copying. An implementation detail: sorting pointers vs. objects can change asymptotic run time - a space for time trade.