# Insertion Sort

### The Insertion Sort Algorithm

To determine the average efficiency of insertion sort consider the number of times that the inner loop iterates. As with other loops featuring nested loops, the number of iterations follows a familiar pattern: 1 + 2 + ... + (n - 2) + (n - 1) = n(n - 1) = O(n 2) . Conceptually, the above pattern is caused by the sorted sublist that is built throughout the insertion sort algorithm. It takes one iteration to build a sorted sublist of length 1, 2 iterations to build a sorted sublist of length two and finally n-1 iterations to build the final list. To determine whether there are any best or worst cases for the sort, we can examine the algorithm to find data sets that would behave differently from the average case with random data. Because the average case identified above locally sorts each sublist there is no arrangement of the aggregate data set that is significantly worse for insertion sort. The nature of the sorting algorithm does however lend itself to perform more efficiently on certain data. In the case where the data is already sorted, insertion sort won't have to do any shifting because the local sublist will already be sorted. That is, the first element will already be sorted, the first two will already be sorted, the first three, and so on. In this case, insertion sort will iterate once through the list, and, finding no elements out of order, will not shift any of the data around. The best case for insertion sort is on a sorted list where it runs is O(n) .

## Take a Study Break

### Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

### Are you afraid of relationships?

Auntie SparkNotes can help!

### Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

### Sexy starlet style

See every single look from the Met Gala!

### Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

### Geeky Actors: Then and Now

Travel back in time!

### Villains We Want These Actresses to Play

From super cute to super bad!

### 10 Movies Better Than Their Books

What do you think?

### How To Look Like J-Law...

When you don't look like J-Law.

### 12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

## The Book

### Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps