From 15e667c1dbcbe9fe3b17cddb2db915a413eb4cc8 Mon Sep 17 00:00:00 2001 From: frigid-lynx <115338534+frigid-lynx@users.noreply.github.com> Date: Sat, 8 Oct 2022 16:55:38 +0530 Subject: [PATCH] Create InsertionSort.java --- InsertionSort.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 InsertionSort.java diff --git a/InsertionSort.java b/InsertionSort.java new file mode 100644 index 0000000..9151e1a --- /dev/null +++ b/InsertionSort.java @@ -0,0 +1,31 @@ +//insertion sort implementation in java +public class InsertionSortExample { + public static void insertionSort(int array[]) { + int n = array.length; + for (int j = 1; j < n; j++) { + int key = array[j]; + int i = j-1; + while ( (i > -1) && ( array [i] > key ) ) { + array [i+1] = array [i]; + i--; + } + array[i+1] = key; + } + } + + public static void main(String a[]){ + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Insertion Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + System.out.println(); + + insertionSort(arr1);//sorting array using insertion sort + + System.out.println("After Insertion Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + } +}