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
Outer loop picks element to insert. - Inner loop shifts larger elements right. - Key placed at correct position. - Together sorts array in ascending order. Conclusion: Shows how insertion sort can be implemented in arrays.