JavaScript
14 Best JavaScript Books for Beginners and Experts [2021 List]
JavaScript is an open-source and most popular client-side scripting language supported by all...
Insertion sort is a simple sorting algorithm suited for small data sets. During each iteration, the algorithm
Here is how the process works graphically
package com.gtupapers;
public class InsertionSortExample {
public static void main(String a[])
{
int[] myArray = {860,8,200,9};
System.out.println("Before Insertion Sort");
printArray(myArray);
insertionSort(myArray);//sorting array using insertion sort
System.out.println("After Insertion Sort");
printArray(myArray);
}
public static void insertionSort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; i++)
{ System.out.println("Sort Pass Number "+(i));
int key = arr[i];
int j = i-1;
while ( (j > -1) && ( arr [j] > key ) )
{
System.out.println("Comparing "+ key + " and " + arr [j]);
arr [j+1] = arr [j];
j--;
}
arr[j+1] = key;
System.out.println("Swapping Elements: New Array After Swap");
printArray(arr);
}
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Before Insertion Sort 860 8 200 9 Sort Pass Number 1 Comparing 8 and 860 Swapping Elements: New Array After Swap 8 860 200 9 Sort Pass Number 2 Comparing 200 and 860 Swapping Elements: New Array After Swap 8 200 860 9 Sort Pass Number 3 Comparing 9 and 860 Comparing 9 and 200 Swapping Elements: New Array After Swap 8 9 200 860 After Insertion Sort 8 9 200 860
JavaScript is an open-source and most popular client-side scripting language supported by all...
What is User Defined Exception in Java? User Defined Exception or custom exception is creating your...
What is Abstraction in Java? Abstraction in JAVA shows only the essential attributes and hides...
What is Interface? The interface is a blueprint that can be used to implement a class. The...
What is Java Array? Java Array is a very common type of data structure which contains all the data...
What is compareTo() method in Java? compareTo() is used for comparing two strings...