Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, October 5, 2016

Insertion Sort - Part 1






Solution by C:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
void insertionSort(int ar_size, int *  ar) {
    int val=ar[ar_size-1],flag=0;
for(int i=ar_size-1;i>=0;i--)
{
    if(val<ar[i-1])
        {
        ar[i]=ar[i-1];
    }
    else
        {
        ar[i]=val;
        flag=1;
    }
   for(int _ar_i = 0; _ar_i < ar_size; _ar_i++) {
        printf("%d ",ar[_ar_i]);
    }
    printf("\n");
    if(flag==1)
        break;
}
}
int main(void) {
    int _ar_size;
    scanf("%d", &_ar_size);
    int _ar[_ar_size], _ar_i;
    for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
        scanf("%d", &_ar[_ar_i]);
    }

    insertionSort(_ar_size, _ar);
    return 0;

}

0 Comments:

Post a Comment

Stats