Insertion Sort Program in Java


import java.util.*;
public class InsertionSort
{
    public static void main(String[] args)
    {
        int arr[] = new int[10];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 10; i++)
        {
            System.out.print("Enter the number ar[" + i + "]:");
            arr[i] = sc.nextInt();
        }
        int n = arr.length;
        
        int temp, j;
        for (int i = 1; i < n; 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 order:");
        for (int i = 0; i < 10; i++)
        {
            System.out.println(arr[i]);
        }
    }
}


Output:

Enter the number ar[0]:5
Enter the number ar[1]:2
Enter the number ar[2]:9
Enter the number ar[3]:19
Enter the number ar[4]:14
Enter the number ar[5]:26
Enter the number ar[6]:3
Enter the number ar[7]:8
Enter the number ar[8]:45
Enter the number ar[9]:62
Sorted order:
2
3
5
8
9
14
19
26
45
62
learn java study java