Kraken -4 years ago 75
C Question

# Implementation of insertion sort

Here's my code.

``````#include<stdio.h>
void insert(int member,int arr[],int size)
{
int i,j;
for(i=0;i<size;i++)
{
if(member<arr[i])
{

for( j=0;j<size-i;j++)
{
arr[size]=arr[size-1];
}
arr[i]=member;
break;
}
}
}
void insertsort(int arr[],int size)
{
int newsize=1,member;
for(newsize=1;newsize<size;newsize++)
{
member=arr[newsize];
insert(member,arr,newsize);
}
}
void main()
{
int arr[100];
int size,i;
printf("enter the size");
scanf("%d",&size);
printf("enter numbers");
for( i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
insertsort(arr,size);
for(i=0;i<size;i++)
printf("\n %d",arr[i]);
}
``````

I dont know what the problem is but on entering

Number of elements : 5;

INPUT NUMBERS 45 23 87 345 12

OUTPUT 12 45 87 345 345.

Can someone tell me what the problem is?

In you inset function, change `arr[size]=arr[size-1];` to `arr[size-j]=arr[size-j-1];`.

When you do the insertion, I guess you wanted to shift all the numbers after the insertion point 1 step right, but instead you only shifted the right most one.

``````void insert(int member,int arr[],int size)
{
int i,j;
for(i=0;i<size;i++)
{
if(member<arr[i])
{
for( j=0;j<size-i;j++)
{
arr[size-j]=arr[size-j-1];
}
arr[i]=member;
break;
}
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download