Question Name:Insertion sort

#include<bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
void insertionSort(int ar_size, int *ar) {
 
    int small = 0;
    for(int i = 0; i < ar_size-1;i++){
     
        if(ar[i] > ar[i+1]){
            small = ar[i+1];
            int j = i;
            while(ar[j] > small){
                ar[j+1] = ar[j];
                j--;
            }
            ar[j+1] = small;
        }
        for(int k = 0; k < ar_size; k++)cout << ar[k] << " ";
        cout << endl;
    }
}
int main(void) {
 
    int _ar_size;
    cin >> _ar_size;
    //scanf("%d", &_ar_size);
    int _ar[_ar_size], _ar_i;
    for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
        cin >> _ar[_ar_i];
    }
   insertionSort(_ar_size, _ar);
   return 0; //sujan
}

Problem Description

Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms.

Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list.

Insert element into sorted list

Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted?

Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.

Guideline: You can copy the value of e to a variable and consider its cell “empty”. Since this leaves an extra cell empty on the right, you can shift everything over until v can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with e .

Input Format

There will be two lines of input:
size – the size of the array
Arr – the unsorted array of integers

Output Format
On each line, output the entire array every time an item is shifted in it.

Constraints

1<=size<=1000
-10000<=e<=10000, e belongs to arr

  • Test Case 1

    Input (stdin)

    5
    2 4 6 8 3
    

    Expected Output

    2 4 6 8 3 
    2 4 6 8 3 
    2 4 6 8 3 
    2 3 4 6 8
  • Test Case 2

    Input (stdin)

    5
    1 0 0 0 2
    

    Expected Output

    0 1 0 0 2 
    0 0 1 0 2 
    0 0 0 1 2 
    0 0 0 1 2 

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro