You are on page 1of 3

Insertion Sort: Introduction

Algorithm for sorting elements in array


Algorithm sorts the numbers in place
Do not have to allocate additional storage
Simply rearranges the numbers in the array

Left side is always sorted


Will see in demonstration

Java implementation will use ArrayLists and Generics


Anything that implements Javas compareTo can be used

Insertion Sort: The Algorithm


Select the element to be compared
Start at the second element (index: 1) and continue to the last
element (index: array to be sorted length 1)

Compare this element to elements preceding it


Exchange with preceding elements until the element to be
compared is greater than a preceding element or the start of
the array is reached

Repeat

Insertion Sort: Analysis


Efficient algorithm for sorting a small number of
elements
Best Case (Already Sorted)
O(n)
Dont have to go through the while loop

Average-Case and Worst Case


O(n2)

You might also like