StackTips

Insertion sort example in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.62K views, updated on Sept. 17, 2023

Code snippet to sort array using insertion sort algorithm in java.

public class InsertionSortExample {
	static int step = 1;

	public static void main(String[] args) {

		int[] array = { 17, 21, 191, 3, 23, 45, 34, 9, 1 };

		int n = array.length;
		for (int j = 1; j < n; j++) {
			int key = array[j];
			int i = j - 1;
			while ((i > -1) && (array[i] > key)) {
				array[i + 1] = array[i];
				i--;
			}
			array[i + 1] = key;
			printNumbers(array);
			
			System.out.println("n");
		}
	}

	private static void printNumbers(int[] input) {
		System.out.println("--- step " + step + " ----");
		step++;

		for (int i = 0; i < input.length; i++) {
			System.out.print(input[i] + ", ");
		}
	}
}

Output
Insertion sort example in Java

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!