Google

Program to insert a value in an array such that array remains sorted

Written on:August 20, 2012
Comments are closed

Sorted insertion in an Array:

Whenever a new value is inserted, appropriate place is located to insert this value.  After locating that place, shifting of elements is required from that position to the last element by one position to the right.  Then the located position may be assigned the new element to be inserted.  The ‘C’ program for the same is given below:

/* Program for sorted insertion */
#include <stdio.h>

#define MAX 10

int main(){
int arr[MAX]={0},n,i,j,k,num,ct=0;
printf(“nEnter total numbers?”);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“nEnter number to insert?”);
scanf(“%d”,&num);
for(j=0;j<ct && arr[j]<=num;j++);
for(k=n-1;k>=j;k–)
arr[k+1] = arr[k];
arr[j] = num;
ct++;
}
printf(“nArray elements are: “);
for(i=0;i<n;i++)
printf(“%dt”,arr[i]);
}

Sorry, the comment form is closed at this time.