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 {
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<arr.length;i++){
/*System.out.println("\nPass "+(i)+" gives us -> ");
System.out.print("\nCurrent ->"+arr[i]);
System.out.print("\nPrevious ->"+arr[i-1]);*/
if(arr[i]<arr[i-1]){
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) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = temp;
i++;
}
System.out.println("After Sorting " + Arrays.toString(nums));
}
}
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<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("]");
}
}