简体   繁体   中英

calculating time complexity for insertion sort

I'm trying to understand the time complexity of insertion sort. I got stuck at while loop. I'm unable to understand how many times while loop executes

InsertionSort(A)
    for j = 2 to A.length
        key = A[j]
        i = j - 1
        while i>0 and A[i]>key
            A[i+1] = A[i]
            i = i - 1
        A[i+1] = key

I know that for loop executes n+1 times and every statement in the loop execute n times while loop also executes n times But, what I don't understand is "How many times statements under while loop executes for both worst and best cases?"

In the worst case, A is sorted in descending order, which means that for the j 'th entry, the inner loop will run j times (give or take a "+1" or "-1"...). Happily, there is a formula for that: as Gauss famously found out spontaneously and under duress , summing up all numbers from 1 to n yields a result of n*(n+1)/2 .

As we only care about complexity and not actual values, we can leave the constant and multiplicative factors off and end up with O(n^2) .

Tongue-in-cheek aside, the fact that there is a loop within a loop is a strong indication for O(n^2) when the inner loop count is bounded linearly - which it is here.

Best case, with A already sorted in ascending order, the inner loop will be entered not at all, and overall complexity will be O(n) .

The average case depends heavily on what your expected "unorderedness" looks like. For example, the sort will behave greatly if your list is basically always sorted already, and there are only very few, very local switchups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM