Insertion Sort Implementation
This program sorts an array using insertion sort algorithm.
Problem Statement
Write a Java program to sort an integer array using insertion sort.
Source Code
| 1 | public class InsertionSort { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {12, 11, 13, 5, 6}; |
| 4 | for(int i=1; i<arr.length; i++) { |
| 5 | int key = arr[i]; |
| 6 | int j = i-1; |
| 7 | while(j>=0 && arr[j] > key) { |
| 8 | arr[j+1] = arr[j]; |
| 9 | j--; |
| 10 | } |
| 11 | arr[j+1] = key; |
| 12 | } |
| 13 | System.out.print("Sorted array: "); |
| 14 | for(int num : arr) System.out.print(num + " "); |
| 15 | } |
| 16 | } |
Program Output
Sorted array: 5 6 11 12 13
Explanation
The outer loop picks each element to insert, and the inner while loop shifts larger elements to the right until the key is placed at its correct position, together sorting the array in ascending order.