Insertion Sort - Part 2


Problem Statement :


In Insertion Sort Part 1, you inserted one element into an array at its correct sorted position. Using the same approach repeatedly, can you sort an entire array?

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.


Function Description

Complete the insertionSort2 function in the editor below.

insertionSort2 has the following parameter(s):

int n: the length of arr
int arr[n]: an array of integers
Prints

At each iteration, print the array as space-separated integers on its own line.

Input Format

The first line contains the integer n, the size of the array arr.
The next line contains n space-separated integers arr[0]  . . . arr[ n - 1 ] .


Constraints

1  <=  n  <=  1000
-10000 <=  arr[ i ]  <=  10000


Output Format

Print the entire array on a new line at every iteration.



Solution :



title-img


                            Solution in C :

In   C++  :








#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;

/* Head ends here */

void insertionSort(vector <int>  ar) {
    int n = ar.size();
    for(int i=1;i<n;i++){
        int curr = ar[i];
        for(int j=i-1;j>=0;j--){
            if(ar[j]>curr){
                ar[j+1]=ar[j];
                if(j==0)
                    ar[j]=curr;
            }
            else{
                ar[j+1]=curr;
                j=-1;
            }
        }
        for(int t=0;t<n;t++)
            cout<<ar[t];
        cout<<endl;
    }
}


/* Tail starts here */
int main() {
    vector <int>  _ar;
    int _ar_size;
    cin >> _ar_size;
    for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
        int _ar_tmp;
        cin >> _ar_tmp;
        _ar.push_back(_ar_tmp); 
    }
    insertionSort(_ar);
    return 0;
}








In   Java  :







import java.util.Scanner;

public class Solution {

 
    public static void main(String[] args) {
       Scanner scan=new Scanner(System.in);
        int s=scan.nextInt();
        int ar[]=new int[s];
        boolean check=false;
        for(int i=0;i<s;i++)
        {
            ar[i]=scan.nextInt();
        }
        for(int i=1;i<s;i++)
        {
            int temp=ar[i];
            for(int j=i-1;j>=0 && temp<ar[j];j--)
            {
                ar[j+1]=ar[j];
                ar[j]=temp;
            }
            for(int j=0;j<s;j++)
                System.out.print(ar[j]+" ");
            System.out.println();
        }
    }
}









In   C  :








#include<stdio.h>
int main()
{
	int size,num,i,j,t;
	int *x;
    scanf("%d",&size);
    x=(int *)malloc(sizeof(int)*size);
    for(i=0;i<size;i++)
    scanf("%d",&x[i]);
    //insertion sort..
    for(i=1;i<size;i++)
    {
    	num=x[i];
    	for(j=i-1;j>=0&&num<x[j];j--)
    	x[j+1]=x[j];
    	x[j+1]=num;
    	for(t=0;t<size;t++)
    	printf("%d ",x[t]);
    	printf("\n");
    }
    
}
    








In   Python3  :







size = int(input())
array = input().split(" ")
arr = ['None'] * size
for i in range(size):
    arr[i] = int(array[i])
i = 1   
while i < size:
    tmp = arr[i]
    j = i - 1
    while arr[j] > tmp and j > -1:
        arr[j+1] = arr[j]       
        j = j - 1 
    arr[j+1] = tmp
    for k in range(size):
        print(arr[k],end = " ")
    print()    
    i = i + 1
                        








View More Similar Problems

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →