Insertion Sort Algorithm - GeeksforGeeks (2024)

Last Updated : 02 Aug, 2024

Comments

Improve

Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.

Insertion sort is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in the sorted group.

Insertion Sort Algorithm:

Insertion sort is a simple sorting algorithm that works by building a sorted array one element at a time. It is considered an ” in-place ” sorting algorithm, meaning it doesn’t require any additional memory space beyond the original array.

Algorithm:

To achieve insertion sort, follow these steps:

  • We have to start with second element of the array as first element in the array is assumed to be sorted.
  • Compare second element with the first element and check if the second element is smaller then swap them.
  • Move to the third element and compare it with the second element, then the first element and swap as necessary to put it in the correct position among the first three elements.
  • Continue this process, comparing each element with the ones before it and swapping as needed to place it in the correct position among the sorted elements.
  • Repeat until the entire array is sorted.

Working of Insertion Sort Algorithm:

Consider an array having elements : {23, 1, 10, 5, 2}

Insertion Sort Algorithm - GeeksforGeeks (1)

First Pass:

  • Current element is 23
  • The first element in the array is assumed to be sorted.
  • The sorted part until 0th index is : [23]

Second Pass:

  • Compare 1 with 23 (current element with the sorted part).
  • Since 1 is smaller, insert 1 before 23 .
  • The sorted part until 1st index is: [1, 23]

Third Pass:

  • Compare 10 with 1 and 23 (current element with the sorted part).
  • Since 10 is greater than 1 and smaller than 23 , insert 10 between 1 and 23 .
  • The sorted part until 2nd index is: [1, 10, 23]

Fourth Pass:

  • Compare 5 with 1 , 10 , and 23 (current element with the sorted part).
  • Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10 .
  • The sorted part until 3rd index is : [1, 5, 10, 23]

Fifth Pass:

  • Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part).
  • Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 .
  • The sorted part until 4th index is: [1, 2, 5, 10, 23]

Final Array:

  • The sorted array is: [1, 2, 5, 10, 23]

To deepen your understanding of sorting algorithms like insertion sort and other essential data structures, consider enrolling in our comprehensive course, Tech Interview 101 – From DSA to System Design . This course covers data structures and algorithms from basic to advanced levels , ensuring you have a solid foundation to excel in technical exams and interviews. Building this knowledge is crucial for your success in the tech industry.

Implementation of Insertion Sort:

C++
// C++ program for insertion sort#include <bits/stdc++.h>using namespace std;// Function to sort an array using// insertion sortvoid insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key,  // to one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }}// A utility function to print an array// of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;}// Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, N); printArray(arr, N); return 0;}// This is code is contributed by rathbhupendra
C
// C program for insertion sort#include <math.h>#include <stdio.h>/* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }}// A utility function to print an array of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");}/* Driver program to test insertion sort */int main(){ int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}
Java
// Java program for implementation of Insertion Sortpublic class InsertionSort { /*Function to sort array using insertion sort*/ void sort(int arr[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } /* A utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }};/* This code is contributed by Rajat Mishra. */
Python
# Python program for implementation of Insertion Sort# Function to do insertion sortdef insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key# Driver code to test abovearr = [12, 11, 13, 5, 6]insertionSort(arr)for i in range(len(arr)): print ("% d" % arr[i])# This code is contributed by Mohit Kumra
C#
// C# program for implementation of Insertion Sortusing System;class InsertionSort { // Function to sort array // using insertion sort void sort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; // Move elements of arr[0..i-1], // that are greater than key, // to one position ahead of // their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print // array of size n static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.Write("\n"); } // Driver Code public static void Main() { int[] arr = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }}// This code is contributed by ChitraNayal.
JavaScript
<script>// Javascript program for insertion sort  // Function to sort an array using insertion sortfunction insertionSort(arr, n) {  let i, key, j;  for (i = 1; i < n; i++)  {  key = arr[i];  j = i - 1;   /* Move elements of arr[0..i-1], that are  greater than key, to one position ahead  of their current position */ while (j >= 0 && arr[j] > key)  {  arr[j + 1] = arr[j];  j = j - 1;  }  arr[j + 1] = key;  } }  // A utility function to print an array of size n function printArray(arr, n) {  let i;  for (i = 0; i < n; i++)  document.write(arr[i] + " ");  document.write("<br>"); }  // Driver code  let arr = [12, 11, 13, 5, 6 ];  let n = arr.length;   insertionSort(arr, n);  printArray(arr, n);  // This code is contributed by Mayank Tyagi </script>
PHP
<?php // PHP program for insertion sort// Function to sort an array// using insertion sortfunction insertionSort(&$arr, $n){ for ($i = 1; $i < $n; $i++) { $key = $arr[$i]; $j = $i-1; // Move elements of arr[0..i-1], // that are greater than key, to  // one position ahead of their  // current position while ($j >= 0 && $arr[$j] > $key) { $arr[$j + 1] = $arr[$j]; $j = $j - 1; } $arr[$j + 1] = $key; }}// A utility function to// print an array of size nfunction printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i]." "; echo "\n";}// Driver Code$arr = array(12, 11, 13, 5, 6);$n = sizeof($arr);insertionSort($arr, $n);printArray($arr, $n);// This code is contributed by ChitraNayal.?>

Output

5 6 11 12 13 

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Complexity Analysis of Insertion Sort :

Time Complexity of Insertion Sort

  • Best case: O(n) , If the list is already sorted, where n is the number of elements in the list.
  • Average case: O(n 2 ) , If the list is randomly ordered
  • Worst case: O(n 2 ) , If the list is in reverse order

Space Complexity of Insertion Sort

  • Auxiliary Space: O(1), Insertion sort requires O(1) additional space, making it a space-efficient sorting algorithm.

Advantages of Insertion Sort:

  • Simple and easy to implement.
  • Stable sorting algorithm.
  • Efficient for small lists and nearly sorted lists.
  • Space-efficient.
  • Adoptive. the number of inversions is directly proportional to number of swaps. For example, no swapping happens for a sorted array and it takes O(n) time only.

Disadvantages of Insertion Sort:

  • Inefficient for large lists.
  • Not as efficient as other sorting algorithms (e.g., merge sort, quick sort) for most cases.

Applications of Insertion Sort:

Insertion sort is commonly used in situations where:

  • The list is small or nearly sorted.
  • Simplicity and stability are important.

Frequently Asked Questions on Insertion Sort

Q1. What are the Boundary Cases of the Insertion Sort algorithm?

Insertion sort takes the maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.

Q2. What is the Algorithmic Paradigm of the Insertion Sort algorithm?

The Insertion Sort algorithm follows an incremental approach.

Q3. Is Insertion Sort an in-place sorting algorithm?

Yes, insertion sort is an in-place sorting algorithm.

Q4. Is Insertion Sort a stable algorithm?

Yes, insertion sort is a stable sorting algorithm.

Q5. When is the Insertion Sort algorithm used?

Insertion sort is used when number of elements is small. It can also be useful when the input array is almost sorted, and only a few elements are misplaced in a complete big array.


Elevate your coding journey with a Premium subscription. Benefit from ad-free learning, unlimited article summaries, an AI bot, access to 35+ courses, and more-available only with GeeksforGeeks Premium! Explore now!


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
Insertion Sort Algorithm - GeeksforGeeks (2024)

FAQs

Is insertion sort a good algorithm? ›

Insertion sort has a fast best-case running time and is a good sorting algorithm to use if the input list is already mostly sorted. For larger or more unordered lists, an algorithm with a faster worst and average-case running time, such as mergesort, would be a better choice.

What is an example of sorting? ›

Sorting is the process of placing elements from a collection in some kind of order. For example, a list of words could be sorted alphabetically or by length. A list of cities could be sorted by population, by area, or by zip code.

What is the insertion sort algorithm in C++? ›

Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array.

What is the complexity of insertion sort? ›

The worst-case (and average-case) complexity of the insertion sort algorithm is O(n²). Meaning that, in the worst case, the time taken to sort a list is proportional to the square of the number of elements in the list. The best-case time complexity of insertion sort algorithm is O(n) time complexity.

What is the main disadvantage of insertion sort? ›

Insertion sort algorithm is a basic sorting algorithm that sequentially sorts each item in the final sorted array or list. It is significantly low on efficiency while working on comparatively larger data sets.

What is the most efficient sorting algorithm? ›

Quicksort is the fastest known comparison-based sorting algorithm when applied to large, unordered, sequences. It also has the advantage of being an in-place (or nearly in-place) sort.

What is a real life example of insertion sort algorithm? ›

Insertion sort strongly resembles how we sort playing cards. To understand how, simply pick every subsequent card from a deck and place it in its proper position by comparing its value. Another real-world example of insertion sort is how tailors arrange shirts in a closet.

What is the simplest sorting algorithm? ›

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

What is the best search algorithm? ›

This type of searching algorithm is used to find the position of a specific value contained in a sorted array. The binary search algorithm works on the principle of divide and conquer and it is considered the best searching algorithm because it's faster to run.

What is the logic of the insertion sorting algorithm? ›

Insertion sort iterates, consuming one input element each repetition, and grows a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

What is the principle of insertion sort algorithm? ›

Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find its correct position i.e, the position to which it belongs in a sorted array.

Why is insertion sort better? ›

Advantages of Insertion Sort:

Simple and easy to understand and implement. Efficient for small data sets or nearly sorted data. In-place sorting algorithm, meaning it doesn't require extra memory. Stable sorting algorithm, meaning it maintains the relative order of equal elements in the input array.

What is the formula for insertion sort comparison? ›

So, the total number of insertion sort comparisons is (N - 1)×1/4N = 1/4(N2 - N) in the average case. To summarize, an insertion sort of N items always requires exactly N - 1 passes through the sorted portion of the list. What varies is the number of comparisons that must be performed per pass.

Why is it called insertion sort? ›

Insertion sort is a sorting algorithm that sorts an array by inserting each element in its correct position in a sorted sub-list. It is called an in-place comparison sorting algorithm because it sorts the input list in place without requiring any extra memory.

Is insertion sort always better than selection sort? ›

When is it more appropriate to use Insertion Sort than Selection Sort? When the array is already mostly sorted at the start. Insertion sort is always faster than selection sort, so any array is appropriate.

What is better insertion sort or quicksort? ›

Quicksort algorithm is efficient if the size of the input is very large. But, insertion sort is more efficient than quick sort in case of small arrays as the number of comparisons and swaps are less compared to quicksort. So we combine the two algorithms to sort efficiently using both approaches.

Is insertion sort good at long lists? ›

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

Is insertion sort better than merge sort? ›

Efficiency: Considering the average time complexity of both algorithms, we can safely say the merge sort is efficient in terms of time and insertion sort is efficient in terms of space.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Arielle Torp

Last Updated:

Views: 5532

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.