Tutorials Java Insertion sort example in Java

Insertion sort example in Java

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

Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Wordpress Tutorials

Include Custom Post Types in Your WordPress RSS Feed

Next Post

ListView Header Parallax in Android

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x