Insertion sort is a sort algorithm very similar to bubble sort; the two even compare and exchange exactly the same pairs of elements, although in a different chronological order. 
Insertion sort is a simple sort algorithm where the result is built up one entry at a time. 
The algorithm is as follows: 
In abstract terms, each iteration of an insertion sort removes an element from the input data, inserting it into the correct sequence in the result, until no elements are left in the input. The choice of which element to remove from the input is arbitrary. The implementation of the result has the greatest impact on the time taken, so an ordered tree data structure with efficient inserts and inorder traversal will give good results. Specific implementations of insertion sort using these data structures may have their own names. Straight insertion sortStraight insertion sort is a very simple implementation of insertion sort. Sorting is done inplace. The result array after n iterations is the first n entries of the input array, where the first remaining entry of the input is removed each time, and the result extends into the input when this entry is inserted: 
def insertionsort(array): 
_____ result ______ ______ input ______  < x  > x  x  ...  </pre> becomes:
The algorithm can be written as follows: <pre> def straightinsertionsort(array): 
Straight insertion sort is very similar to bubble sort. 
Insertion sort (and bubble sort) take O(n^{2}) time in the average, best, and worst cases, which makes them impractical for sorting large numbers of elements; however, their inner loops are very fast, which often makes them the fastest algorithms around for sorting small numbers of elements, typically less than 10 or so. Quicksort works by dividing the array to be sorted into smaller runs to be sorted separately; highly optimized implementations of Quicksort often use insertion or bubble sort to sort these runs once they get small enough. More sophisticated versions of insertion sort can be smart enough to figure out how much of their data is already in order, and can therefore grow their sorted region by more than one item on each pass; these versions of insertion sort will finish in one pass if the whole array is already sorted. 
In the best case of an already sorted array, this implementation of straight insertion sort takes O(n) time: each iteration, the first remaining element of the input is only compared with the last element of the result. It takes O(n^{2}) time in the average and worst cases, which makes it impractical for sorting large numbers of elements; however, the inner loop is very fast, which often makes it one of the fastest algorithms around for sorting small numbers of elements, typically less than 10 or so. Quicksort works by dividing the array to be sorted into smaller runs to be sorted separately; highly optimized implementations of Quicksort often use insertion or bubble sort to sort these runs once they get small enough. 
 
