Insertion Sort - Part 1

  • + 0 comments

    Java easy code:

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class MyClass {
        
        public static void main(String args[]) {
          
            // Initialize Scanner to take input from the user
            Scanner in = new Scanner(System.in);
            
            // Read the size of the array
            int n = in.nextInt();
            int[] arr = new int[n];
            
            // Input all elements of the array
            for(int i = 0; i < n; i++) {
                arr[i] = in.nextInt();
            }
            
            // Store the last element of the array (key to be inserted)
            int curr = arr[n-1];
            int i = 0;
            
            // Loop to shift elements to the right if they are greater than 'curr'
            for(i = n - 2; i >= 0; i--) {
                // If the current element is smaller than 'curr', place 'curr' here
                if(arr[i] < curr) {
                    arr[i+1] = curr;
                    break; // Exit the loop after insertion
                } else {
                    // Shift the element to the right
                    arr[i+1] = arr[i];
                }
                
                // Print the array after each shift
                for(int j = 0; j < n; j++) {
                    System.out.print(arr[j] + " ");
                }
                System.out.println();
            }
            
            // If no valid position was found in the loop, place 'curr' at the beginning
            if (i == -1) {
                arr[0] = curr;
            }
            
            // Print the final state of the array
            for(int j = 0; j < n; j++) {
                System.out.print(arr[j] + " ");
            }
        }
    }