StackTips

Insertion sort example in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.52K 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

Java Collection APIs

The Collections framework in Java defines numerous different data structures in which you can store, group, and retrieve objects.

>> CHECK OUT THE COURSE

Keep exploring

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!