From a8152f621bf2a0705fc39497cd9fec01559850f5 Mon Sep 17 00:00:00 2001 From: Godhuli Sarkar <102232303+Godhuli07@users.noreply.github.com> Date: Mon, 17 Oct 2022 22:23:49 +0530 Subject: [PATCH] Create Insertion_sort --- Insertion_sort | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Insertion_sort diff --git a/Insertion_sort b/Insertion_sort new file mode 100644 index 0000000..cf7197b --- /dev/null +++ b/Insertion_sort @@ -0,0 +1,44 @@ +// Java program for implementation of Insertion Sort +class InsertionSort { + /*Function to sort array using insertion sort*/ + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 5,3,9,3,1 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} /* This code is contributed by Rajat Mishra. */