Program In Java To Sort The Given Array Using Insertion Sort Algorithm.
The Following Program Reads The Elements Of An Array From User And Then It Sorts The Array In Ascending Order Using Insertion Sort Algorithm And Displays The Sorted Array
import java.io.*; class Insertion { void iSort(int[] a) //Insertion Sort Algorithm { int i, j, k, cmp = 0; for (i = 1; i < a.length; i++) { k = a[i]; for (j = i - 1; j >= 0 && a[j] > k; j--, cmp++) a[j + 1] = a[j]; a[j + 1] = k; } System.out.println("\n\nNo.Of Comparisons For " + a.length + " Element is " + cmp); } public static void main(String[] arg) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Total Number Of Elements In An Array::"); int t = Integer.parseInt(br.readLine()); int[] arr = new int[t]; for (int i = 0; i < t; i++) { System.out.print("\nEnter Element::"); int e = Integer.parseInt(br.readLine()); arr[i] = e; } //int []arr={5,4,15,16,17,3,2,1}; Insertion ins = new Insertion(); ins.iSort(arr); System.out.println("\n\nAfter Sorting Array Is::"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); } }
OUTPUT:
Enter Total Number Of Elements In An Array::8 Enter Element::5 Enter Element::4 Enter Element::15 Enter Element::16 Enter Element::17 Enter Element::3 Enter Element::2 Enter Element::1
No.Of Comparisons For 8 Element is 19
After Sorting Array Is:: 1 2 3 4 5 15 16 17