Given a sorted list with an unsorted number V in the right-most cell, can you write some simple code to insert V into the array so it remains sorted?
i.e.,Given an already sorted array, you have to perform a sorted insert of an element , so that after inserting the element into the array, the array should remain sorted.
Print the array every time a value is shifted in the array until the array is fully sorted.
Method 1:
You can copy the value of V to a variable and keep on shifting everything over until V can be inserted. When you reach the right position, you can place V in its right position.
Implementation:
i.e.,Given an already sorted array, you have to perform a sorted insert of an element , so that after inserting the element into the array, the array should remain sorted.
Print the array every time a value is shifted in the array until the array is fully sorted.
Method 1:
You can copy the value of V to a variable and keep on shifting everything over until V can be inserted. When you reach the right position, you can place V in its right position.
Implementation:
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> void insertionSort(int ar_size, int * ar) { int v; v=ar[ar_size-1]; for(int i=ar_size-2;i>=0;i--) { if(ar[i]>v) ar[i+1]=ar[i]; else ar[i+1]=v; for(int j=0;j<ar_size;j++) { printf("%d ",ar[j]); } printf("\n"); } } 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; }