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  ...

Conditional Statements | if, If-else, "if" and "if else", Switch Break | Complete Java Placement Course | Lecture 3

                                    Java - Introduction to Programming Lecture 3 Conditional Statements Conditional statements are a fundamental concept in programming. They are used to make decisions based on certain conditions, allowing the program to perform different actions depending on the input or data it receives. In this article, we'll take a closer look at conditional statements in programming and how they can be used effectively. What are conditional statements? Conditional statements, also known as "if-then" statements, are used in programming to execute certain code if a condition is met. In other words, the program will perform a particular action if a particular condition is true. For example, a program may check if a user has ent...