Skip to main content

Posts

Showing posts with the label insertion sort

Types of Sorting-IMPORTANT CONCEPTS

1) Bubble Sort Algorithm:  1.Traverse the array from i=0 to length-2 2. Inside it traverse the array from j=0 to length-2-i 2.1. If a[j]>a[j+1], swap them Code: import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner (System.in); int m = sc.nextInt(); for(int mi=0;mi<m;mi++){    int n = sc.nextInt();    int a[]= new int [n];    boolean swapped=false;    for(int i1=0;i1<n;i1++){        a[i1]=sc.nextInt();    }    for(int i=0;i<n-1;i++){        for(int j=0;j<n-1-i;j++){            if(a[j]>a[j+1]){                int temp=a[j];                a[j]=a[j+1];                a[j+1]=temp; ...

Insertion Sort [EASY/IMP]

Company: Veritas, MAQ-Software, Juniper, Grofers, Dell, Cisco, Accenture Question: Perform Insertion sort CODE: /* Function to sort an array using insertion sort void insertionSort(int arr[], int n) {   GfG obj = new GfG();    for (int i = 1; i < n; i++)       obj.insert(arr, i); } */ class GfG {   // Function to sort an array using insertion sort   void insert(int arr[],int i)   {        int key=arr[i];        int j=i-1;        while (j>=0 && arr[j] > key)             {                 arr[j+1] = arr[j];                 j = j-1;             }             arr[j+1] = key;   } } EXECUTION TIME:0.4s