Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

How to Implement Insertion Sort Algorithm in Java? Detailed Example Attached

$
0
0

Java Insertion Sort algorithm logic is one of the many simple questions asked in Interview Questions. It sorts array a single element at a time. Very efficient for relatively small to medium set of arrays. Insertion sort is not recommended for large set of arrays.

Take a look at Bubble Sort and Selection Sort algorithm for comparison.

Insertion Sort Logic is very simple

Every iteration, smallest element will be added to unsorted array. Let’s consider this scenario.

  • You have 10 elements in array.
  • 1st iteration puts smallest element into the position 1. We will call it as sorted array. Remaining 9 elements will call as unsorted array.
  • Now in 2nd iteration, smallest element from unsorted array will be put into 1st position. Now, there will be 2 elements in sorted array and 8 elements into unsorted array.
  • Same iteration will continue until we reached to 0 element in unsorted array.

Let’s get started

  • Create class CrunchifyInsertionSortAlgorithm.java
  • Add total 11 elements to array crunchifyArray
  • Print unsorted array first
  • Now sort array using InsertionSort Algorithm
  • After each iteration print array Value for debugging
  • Print final sorted array and verify

Here is an Insertion Sort Source Code

package crunchify.com.tutorial;

/**
 * @author Crunchify.com 
 * Insertion Sort Algorithm in Java
 * 
 */

public class CrunchifyInsertionSortAlgorithm {

	public static void main(String[] args) {

		// Let's start with arraySize 11
		int arraySize = 11;

		CrunchifyInsertionSortArray crunchifyArray;
		crunchifyArray = new CrunchifyInsertionSortArray(arraySize);

		crunchifyArray.insert(10);
		crunchifyArray.insert(17);
		crunchifyArray.insert(-9);
		crunchifyArray.insert(1);
		crunchifyArray.insert(8);
		crunchifyArray.insert(33);
		crunchifyArray.insert(7);
		crunchifyArray.insert(35);
		crunchifyArray.insert(15);
		crunchifyArray.insert(21);
		crunchifyArray.insert(4);

		System.out.print("Here is our initial array: ");
		CrunchifyInsertionSortArray.log();

		CrunchifyInsertionSortArray.crunchifyInsertionSort();

		System.out.print("Here is our final array after insertion sort: ");
		CrunchifyInsertionSortArray.log();

	}

}

/**
 * Insertion Sort Algorithm
 */
class CrunchifyInsertionSortArray {

	private static int[] crunchifyObject;
	private static int crunchifyIndex; // Default index is 0

	/**
	 * Simple constructor
	 */
	public CrunchifyInsertionSortArray(int arraySize) {
		crunchifyObject = new int[arraySize];
		crunchifyIndex = 0;
	}

	/**
	 * Insert an Array
	 */
	public void insert(int crunchifyValue) {
		crunchifyObject[crunchifyIndex++] = crunchifyValue;
	}

	/**
	 * Acutal Insertion Sort Logic goes here...
	 */
	public static void crunchifyInsertionSort() {
		int tmpObj, obj1, obj2;

		// Counter to print iteration
		int counter = 1;

		for (obj2 = 1; obj2 < crunchifyObject.length; obj2++) {
			obj1 = obj2 - 1;
			tmpObj = crunchifyObject[obj2];
			while ((obj1 >= 0) && (tmpObj < crunchifyObject[obj1])) {
				crunchifyObject[obj1 + 1] = crunchifyObject[obj1];
				obj1--;
			}
			crunchifyObject[obj1 + 1] = tmpObj;
			// Let's print array after each iteration
			log("Iteration " + counter);
			counter++;

		}
	}

	private static void log(String string) {
		System.out.println(" ========= " + string + " ========= ");
		log();
	}

	/**
	 * Let's display Array
	 */
	public static void log() {
		for (int i = 0; i < crunchifyIndex; i++)
			System.out.print(crunchifyObject[i] + " ");
		System.out.println("\n");
	}

}

Run above program in Eclipse. You could modify integer values if you want or use random method to add elements into Integer Array.

Above java example will work for you if you have any of below questions:

  • Write a program for Insertion Sort in java
  • Implement insertion sort in java
  • Java Program to Implement Insertion Sort

Eclipse Console Output:

Here is our initial array: 10 17 -9 1 8 33 7 35 15 21 4 

 ========= Iteration 1 ========= 
10 17 -9 1 8 33 7 35 15 21 4 

 ========= Iteration 2 ========= 
-9 10 17 1 8 33 7 35 15 21 4 

 ========= Iteration 3 ========= 
-9 1 10 17 8 33 7 35 15 21 4 

 ========= Iteration 4 ========= 
-9 1 8 10 17 33 7 35 15 21 4 

 ========= Iteration 5 ========= 
-9 1 8 10 17 33 7 35 15 21 4 

 ========= Iteration 6 ========= 
-9 1 7 8 10 17 33 35 15 21 4 

 ========= Iteration 7 ========= 
-9 1 7 8 10 17 33 35 15 21 4 

 ========= Iteration 8 ========= 
-9 1 7 8 10 15 17 33 35 21 4 

 ========= Iteration 9 ========= 
-9 1 7 8 10 15 17 21 33 35 4 

 ========= Iteration 10 ========= 
-9 1 4 7 8 10 15 17 21 33 35 

Here is our final array after insertion sort: -9 1 4 7 8 10 15 17 21 33 35

The post How to Implement Insertion Sort Algorithm in Java? Detailed Example Attached appeared first on Crunchify.

Author: App Shah


Viewing all articles
Browse latest Browse all 1037

Trending Articles