Skip to main content

Insertion Sort Algorithm

Published 1 min readMarkdown

Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists compared to more advanced algorithms like Merge Sort or Quick Sort, but it performs well for small lists or partially sorted lists. The basic idea of Insertion Sort is to divide the array into a sorted and an unsorted part, then repeatedly pick elements from it and insert them into their correct position within the sorted part.

import java.util.Arrays;

public class InsertionSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    int[] arr= {1,2,3,5,4,7};
    insertion(arr);
    System.out.print(Arrays.toString(arr));
    }
    static void insertion(int[] arr) {
        for(int i=0;i<arr.length-1;i++) {
            for(int j=i+1;j>0;j--) {
                if(arr[j]<arr[j-1]) {
                    swap(arr, j,j-1);
                }
                else {
                    break;
                }
            }
        }
    }
    static void swap(int[] arr, int j, int k) {
        int temp = arr[j];
        arr[j] =arr[k];
        arr[k]=temp;
    }

}

About the author

  • I am a Student who lives and breathe Software development.

No comments yet. Be the first to comment.