From 6abafeed081e41b94857cd55c61a14389bf02548 Mon Sep 17 00:00:00 2001 From: Vedeesh Dwivedi Date: Thu, 8 Dec 2022 20:46:42 +0530 Subject: [PATCH] Update insertion-sort.java The advantage of this code over the previous one is that first of all, it takes user-defined input rather than predefined, and also it has a more user-friendly way of understanding algo for every beginner or pro because you can comment out a few lines of code to see how the result is being calculated stepwise. --- algorithms/Java/sorting/insertion-sort.java | 78 ++++++++++++++------- 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/algorithms/Java/sorting/insertion-sort.java b/algorithms/Java/sorting/insertion-sort.java index 95a996e3..ae8e1db1 100644 --- a/algorithms/Java/sorting/insertion-sort.java +++ b/algorithms/Java/sorting/insertion-sort.java @@ -1,29 +1,59 @@ -import java.util.Arrays; - +import java.util.Scanner; +//uncomment to see steps working.... public class InsertionSort { - static int[] nums = { 12, 43, 2, 4, 1, 0, -23, -93 }; - public static void main(String[] args) { - System.out.println("Before sorting " + Arrays.toString(nums)); - sort(nums); - } + public void InsSort(int arr []) { + int temp; - public static void sort(int[] nums) { - int i = 1; - while (i < nums.length) { - int temp, j; - temp = nums[i]; - j = i; + for(int i=1;i "); + System.out.print("\nCurrent ->"+arr[i]); + System.out.print("\nPrevious ->"+arr[i-1]);*/ + if(arr[i]0;j++){ + if(j>i){break;} + //System.out.print("\nExchange -> Yes"); + while (arr[i-j+1]i-1){break;} //done to eliminate error on line 24 for (i-j-1)=(-1) + System.out.print("\nUpdated Current ->"+arr[i-j]); + System.out.print("\nUpdated Previous ->"+arr[i-j-1]);*/ + } + } + }else{//System.out.print("\nExchange -> No"); + } + /*System.out.println("\n"); + for(int k=0;k 0 && nums[j - 1] > temp) { - nums[j] = nums[j - 1]; - j--; - } - nums[j] = temp; - i++; - } - System.out.println("After Sorting " + Arrays.toString(nums)); - - } -} \ No newline at end of file + public static void main(String[] args) { + int len; + + InsertionSort obj = new InsertionSort(); + Scanner scan = new Scanner(System.in); + System.out.print("No. of elements in array -> "); + len = scan.nextInt(); + int array[] = new int[len]; + for(int i=0;i [ "); + obj.Printarray(array);System.out.print("]"); + obj.InsSort(array); + System.out.print("\nHence, Sorted array using Insertion sort is -> [ "); + obj.Printarray(array);System.out.print("]"); + } +}