Insertion Sorting using Java Program

In this tutorial, We will show you how to perform >Insertion Sorting using Java Program. The example program has been tested and output is shared in the same post.

InsertionSort.java

The Insertion Sort is one of the sorting algorithm to sort the given elements in the array. The following Java class ie: InsertionSort.java contains the logic of insertion sort.

package com.dineshkrish.sort;
import java.util.Scanner;
public class InsertionSort {
// Insertion Sort Logic
public static int[] sort(int[] numbers) {
int temp;
for (int i = 1; i < numbers.length; i++) {
for (int j = i; j > 0; j--) {
if (numbers[j] < numbers[j - 1]) {
temp = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = temp;
}
}
}
return numbers;
}
// Printing the Result
public static void printResult(int[] numbers) {
System.out.println("Insertion Sort");
System.out.println("------------------------");
int len = numbers.length;
if (len > 0) {
for (int i = 0; i < len; i++) {
if (i == len - 1) {
System.out.print(numbers[i] + "");
} else {
System.out.print(numbers[i] + ", ");
}
}
}
}
public static void main(String a[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many numbers you want to sort ?");
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter the " + (i + 1) + " number : ");
numbers[i] = scanner.nextInt();
}
int[] sortedNumbers = sort(numbers); // Sorting Method Invocation
printResult(sortedNumbers); // Printing Result Method Invocation
}
}

Output

—————-
How many numbers you want to sort ?
5
Enter the 1 number : 3
Enter the 2 number : 4
Enter the 3 number : 1
Enter the 4 number : 5
Enter the 5 number : 2
Insertion Sort
————————
1, 2, 3, 4, 5

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *