Insertion Sort - Part 2

Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an array with just the first element, it is already sorted since there's nothing to compare it to.

In this challenge, print the array after each iteration of the insertion sort, i.e., whenever the next element has been inserted at its correct position. Since the array composed of just the first element is already sorted, begin printing after placing the second element.


Example:

Input:  n=6, arr[]={1,4,3,5,6,2}

Output:

1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6

Approach

Java


import java.util.Arrays;

public class InsertionSortPart2 {
    public static void main(String[] args) {
        int n = 6;
        int[] arr = { 143562 };

        insertionSort2(n, arr);
    }

    private static void insertionSort2(int nint[] arr) {
        for (int i = 0; i < n; i++) {
            int tmp = arr[i];
            int j = i;
            while (j > 0 && arr[j - 1] > tmp) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = tmp;
            if (i != 0) {
                Arrays.stream(arr).forEach(e -> System.out.print(e + " "));
                System.out.println();
            }
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

void insertionSort2(int nvector<intarr)
{
    for (int i = 1i < ni++)
    {
        int x = arr[i];
        int j = i;
        while (j > 0 && arr[j - 1] > x)
        {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = x;
        for (int k = 0k < nk++)
            cout << arr[k] << " ";
        cout << "\n";
    }
}
int main()
{
    int n = 6;
    vector<intarr = {143562};
    insertionSort2(narr);
    return 0;
}


No comments:

Post a Comment