Java Program to sort an array using Insertion Sort
Program
import java.util.Scanner;
class InsertionSort {
public static void main(String[] args) {
InsertionSort sort = new InsertionSort();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:\t");
int count = sc.nextInt();
int[] arr = new int[count];
System.out.println("Enter elements");
for (int i = 0; i < arr.length; i++)
arr[i] = sc.nextInt();
sort.insertionSort(arr);
}
void insertionSort(int arr[]) {
int i, j, temp;
for (i = 0; i < arr.length; i++) {
temp = arr[i];
j = i - 1;
while ((j >= 0) && (arr[j] > temp)) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
System.out.println("Sorted Elements:");
for (i = 0; i < arr.length; i++)
System.out.print(arr[i] + "\t");
System.out.println();
}
}
Output
Enter the size of the array:
6
Enter elements
32
68
78
12
-3
98
Sorted Elements:
-3 12 32 68 78 98