Type the Question

Saturday, February 16, 2019

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 

No comments:

Post a Comment

Question Name:TOWER OF HANOI

#include < bits / stdc ++. h > #define lli long long using namespace std ; lli dp [ 202 ]; int main () { int t , n ; ...