Skip to main content

Insertion Sort | Insertion sort algorithm | insertion sort time complexity

                                                               Sorting in JAVA

Insertion Sort

Insertion sort is a simple and efficient sorting algorithm used to sort small or partially sorted arrays. It works by comparing each element in the array to the ones before it and inserting it into its correct position. In this blog post, we will discuss how insertion sort works, its advantages, disadvantages, and its implementation in code.

How does insertion sort work?

Insertion sort starts by comparing the second element in the array to the first element. If the second element is smaller than the first, they swap positions. The algorithm then compares the third element to the first two and inserts it into its correct position. The process continues until all the elements in the array are sorted.


Advantages of insertion sort:-

One of the primary advantages of insertion sort is that it is a simple algorithm to implement. It is also very efficient for small arrays and partially sorted arrays. Additionally, it does not require any extra space as it sorts the array in place.

Disadvantages of insertion sort:-

One of the main disadvantages of insertion sort is that it is not efficient for large arrays. It has a time complexity of O(n^2), which means that the time it takes to sort an array grows exponentially with the size of the array. Additionally, it is not suitable for sorting arrays with a large number of duplicates as it takes longer to sort arrays with repeated elements.

Implementing insertion sort in code:-


The implementation of insertion sort in code is relatively simple. Here is a sample implementation in Python:

less
def insertion_sort(arr): 
for i in range(1, len(arr)):
key = arr[i] j = i - 1 
while j >= 0 and arr[j] > key
arr[j + 1] = arr[j]
j -= 1 
arr[j + 1] = key 
return arr


In this implementation, we first loop through the array starting from the second element. We then assign the second element to a variable called key. We then compare the key to the previous elements in the array and move them one position to the right until we find the correct position for the key. We then insert the key into its correct position.


Here's an implementation of insertion sort in Java:


Idea: Take an element from the unsorted array, place it in its corresponding position in the sorted part, and shift the elements accordingly. 

Time Complexity: O(N2


Code

import java.util.*;

 

class Sorting {

   public static void printArray(int arr[]) {

       for(int i=0; i<arr.length; i++) {

           System.out.print(arr[i]+" ");

       }

       System.out.println();

   }

 

   public static void main(String args[]) {

       int arr[] = {7, 8, 1, 3, 2};

 

       //insertion sort

       for(int i=1; i<arr.length; i++) {

           int current = arr[i];

           int j = i - 1;

               while(j >= 0 && arr[j] > current) {

                   //Keep swapping

                   arr[j+1] = arr[j];

                   j--;

               }

           arr[j+1] = current;

       }

       printArray(arr);

   }

}





Here's an implementation of insertion sort in C++:


cpp
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
 key = arr[i]; 
 j = i - 1
while (j >= 0 && arr[j] > key) { 
 arr[j + 1] = arr[j];
 j = j - 1
 }
 arr[j + 1] = key; 
 } 
}




Here's an implementation of insertion sort in C:


c
void insertionSort(int arr[], int n) {
int i, key, j; 
for (i = 1; i < n; i++) {
 key = arr[i];
 j = i - 1
while (j >= 0 && arr[j] > key) { 
 arr[j + 1] = arr[j];
     j = j - 1;
 } 
      arr[j + 1] = key;
 } 
}



The C++ and C implementations are virtually identical since the syntax for both languages is quite similar. The only difference between the two is the function signature, which includes the return type in C++ and doesn't include it in C.


Conclusion:-


Insertion sort is a simple and efficient sorting algorithm that is ideal for small and partially sorted arrays. Although it is not suitable for large arrays, its ease of implementation and lack of extra space requirements make it an attractive option for small arrays.




Others related blog:-



Comments

Popular posts from this blog

Enter 3 numbers from the user & make a function to print their average in java, c++, python, java.

Enter 3 numbers from the user & make a function to print their average. To find the average of three numbers, you need to add the three numbers together and then divide the sum by three. Here's how you can write a function in C++, C, Python, and Java to take three numbers from the user and calculate their average: JAVA import java . util .*; public class Solutions {     public static void main ( String args []) {        Scanner sc = new Scanner ( System . in );        int a = sc . nextInt ();        int b = sc . nextInt ();        int c = sc . nextInt ();          int average = ( a + b + c ) / 3 ;        System . out . println ( average );    }    }   C++: // c++ #include <iostream> using namespace std ;...

2D Arrays | Java Complete Placement Course | Lecture 11

Java - Introduction to Programming Lecture 11 2D Arrays In Java It is similar to 2D matrices that we studied in 11th and 12th class. Creating a 2D Array - with new keyword int [][] marks = new int [ 3 ][ 3 ] ; Taking a matrix as an input and printing its elements. import java . util .*;   public class TwoDArrays {     public static void main ( String args []) {         Scanner sc = new Scanner ( System . in );         int rows = sc . nextInt ();         int cols = sc . nextInt ();           int [][] numbers = new int [ rows ][ cols ];           //input         //rows         for ( int i = 0 ; i < rows ; i ++) {             //columns  ...

Merge Sort | How do I learn merge sort?

       Merge Sort | For Beginners | Java Placement Course >> Merge sort is a popular sorting algorithm that utilizes a divide-and-conquer approach to sort elements in an array. The basic idea behind merge sort is to divide an unsorted array into two halves, recursively sort each half, and then merge the two sorted halves into a single sorted array. >>  Merge sort algorithm works by recursively dividing an array into two halves, sorting each half, and then merging them to obtain the sorted array. The basic steps of the merge sort algorithm are as follows: Divide the unsorted array into two halves, mid and left. Sort the left half recursively using merge sort algorithm. Sort the right half recursively using merge sort algorithm. Merge the two sorted halves to obtain the final sorted array. JAVA Implementation: // Merge sort public class MergeSort {     //time complexity=nlogn     public static void conquer ( int arr [], int ...