Analysis of Insertion Sort
Understand how insertion sort works by analyzing its time complexity in different scenarios including worst case, best case, average, and almost sorted arrays. Learn why it takes quadratic time in the worst case but can run linearly with nearly sorted data. This lesson explains how the sliding of elements affects performance and helps you grasp when insertion sort is efficient.
We'll cover the following...
Like selection sort, insertion sort loops over the indices of the array. It just calls insert on the elements at indices indexOfMinimum took an amount of time that depended on the size of the sorted subarray, so does each call to insert. Actually, the word "does" in the previous sentence should be "can," and we'll see why.
Let's take a situation where we call insert and the value being inserted into a subarray is less than every element in the subarray. For example, if we're inserting
Suppose that upon every call to insert, the value being inserted is less than every element in the subarray to its left. When we call insert the first time,