 Design and Analysis of Algorithms
 Home
 Basics of Algorithms
 DAA  Introduction
 DAA  Analysis of Algorithms
 DAA  Methodology of Analysis
 Asymptotic Notations & Apriori Analysis
 DAA  Space Complexities
 Design Strategies
 DAA  Divide & Conquer
 DAA  MaxMin Problem
 DAA  Merge Sort
 DAA  Binary Search
 Strassen’s Matrix Multiplication
 DAA  Greedy Method
 DAA  Fractional Knapsack
 DAA  Job Sequencing with Deadline
 DAA  Optimal Merge Pattern
 DAA  Dynamic Programming
 DAA  01 Knapsack
 Longest Common Subsequence
 Graph Theory
 DAA  Spanning Tree
 DAA  Shortest Paths
 DAA  Multistage Graph
 Travelling Salesman Problem
 Optimal Cost Binary Search Trees
 Heap Algorithms
 DAA  Binary Heap
 DAA  Insert Method
 DAA  Heapify Method
 DAA  Extract Method
 Sorting Methods
 DAA  Bubble Sort
 DAA  Insertion Sort
 DAA  Selection Sort
 DAA  Quick Sort
 DAA  Radix Sort
 Complexity Theory
 Deterministic vs. Nondeterministic Computations
 DAA  Max Cliques
 DAA  Vertex Cover
 DAA  P and NP Class
 DAA  Cook’s Theorem
 NP Hard & NPComplete Classes
 DAA  Hill Climbing Algorithm
 DAA Useful Resources
 DAA  Quick Guide
 DAA  Useful Resources
 DAA  Discussion
 Selected Reading
 UPSC IAS Exams Notes
 Developer's Best Practices
 Questions and Answers
 Effective Resume Writing
 HR Interview Questions
 Computer Glossary
 Who is Who
Design and Analysis Insertion Sort
Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game.
The numbers, which are needed to be sorted, are known as keys. Here is the algorithm of the insertion sort method.
Algorithm: 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
Analysis
Run time of this algorithm is very much dependent on the given input.
If the given numbers are sorted, this algorithm runs in O(n) time. If the given numbers are in reverse order, the algorithm runs in O(n^{2}) time.
Example
Unsorted list: 

1^{st} iteration:
Key = a[2] = 13
a[1] = 2 < 13
Swap, no swap 

2^{nd} iteration:
Key = a[3] = 5
a[2] = 13 > 5
Swap 5 and 13 

Next, a[1] = 2 < 13
Swap, no swap 

3^{rd} iteration:
Key = a[4] = 18
a[3] = 13 < 18,
a[2] = 5 < 18,
a[1] = 2 < 18
Swap, no swap 

4^{th} iteration:
Key = a[5] = 14
a[4] = 18 > 14
Swap 18 and 14 

Next, a[3] = 13 < 14,
a[2] = 5 < 14,
a[1] = 2 < 14
So, no swap 

Finally,
the sorted list is 
