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 = { 1, 4, 3, 5, 6, 2 };insertionSort2(n, arr);}private static void insertionSort2(int n, int[] 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 n, vector<int> arr){for (int i = 1; i < n; i++){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 = 0; k < n; k++)cout << arr[k] << " ";cout << "\n";}}int main(){int n = 6;vector<int> arr = {1, 4, 3, 5, 6, 2};insertionSort2(n, arr);return 0;}
No comments:
Post a Comment