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.
pull/1097/head
Vedeesh Dwivedi 2022-12-08 20:46:42 +05:30 committed by GitHub
parent e60d299077
commit 6abafeed08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 54 additions and 24 deletions

View File

@ -1,29 +1,59 @@
import java.util.Arrays; import java.util.Scanner;
//uncomment to see steps working....
public class InsertionSort { public class InsertionSort {
static int[] nums = { 12, 43, 2, 4, 1, 0, -23, -93 };
public static void main(String[] args) { public void InsSort(int arr []) {
System.out.println("Before sorting " + Arrays.toString(nums)); int temp;
sort(nums);
}
public static void sort(int[] nums) { for(int i=1;i<arr.length;i++){
int i = 1; /*System.out.println("\nPass "+(i)+" gives us -> ");
while (i < nums.length) { System.out.print("\nCurrent ->"+arr[i]);
int temp, j; System.out.print("\nPrevious ->"+arr[i-1]);*/
temp = nums[i]; if(arr[i]<arr[i-1]){
j = i; for(int j=1;j>0;j++){
if(j>i){break;}
//System.out.print("\nExchange -> Yes");
while (arr[i-j+1]<arr[i-j]){
temp=arr[i-j];
arr[i-j]=arr[i-j+1];
arr[i-j+1]=temp;
/*if(j>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<arr.length;k++){
System.out.print(arr[k]+" ");
}
System.out.print("\n");*/
}
}
public void Printarray(int arr []) { //Function to print array
for(int j=0;j<arr.length;j++){
System.out.print(arr[j]+" ");
}
}
while (j > 0 && nums[j - 1] > temp) { public static void main(String[] args) {
nums[j] = nums[j - 1]; int len;
j--;
} InsertionSort obj = new InsertionSort();
nums[j] = temp; Scanner scan = new Scanner(System.in);
i++; System.out.print("No. of elements in array -> ");
} len = scan.nextInt();
System.out.println("After Sorting " + Arrays.toString(nums)); int array[] = new int[len];
for(int i=0;i<len;i++){
} array[i]=scan.nextInt();
} }
scan.close();
System.out.print("\nHence, we have the input array as -> [ ");
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("]");
}
}