Insertion Sort - Part 2

  • + 0 comments

    My java solution to convert list to arr and print arr

    import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.function.; import java.util.regex.; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList;

    class Result {

    /*
     * Complete the 'insertionSort2' function below.
     *
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER_ARRAY arr
     */
    
    
    public static void print(int[] arr){
    
    
       for (int i : arr){
    
        System.out.print(i + " ");
       }
            System.out.println("");
    
    }
    
    // {12, 11, 7, 19, 2}
    // {12, 12, 7, 19, 2}
    public static void insertionSort2(int n, int[] arr) {
    // Write your code here
    
        for (int i = 1; i < n; i++){
            int j = i -1;
            int key = arr[i];
    
            while ( j>= 0 && arr[j] > key){
                arr[j + 1] = arr[j];
    
                j--;
            }
    
            arr[j+1] = key;
            Result.print(arr);
        }
    
    }
    

    }

    public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());
    
        int[] arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt).mapToInt(Integer::intValue).toArray();
    
        Result.insertionSort2(n, arr);
    
        bufferedReader.close();
    }
    

    }