Skip to content

Instantly share code, notes, and snippets.

@murikadan
Created September 2, 2012 06:11
Show Gist options
  • Save murikadan/3595271 to your computer and use it in GitHub Desktop.
Save murikadan/3595271 to your computer and use it in GitHub Desktop.
Inserting an element into a sorted array
int binpos(int *,int,int,int);
int insert(int *,int,int);
int binpos(int *a,int low,int high,int key)
{
int mid=0;
while(high>=low)
{
mid=(low+high)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
high=mid-1;
else
low=mid+1;
}
return mid;
}
int insert(int a[],int r,int key)
{
int pos=binpos(a,0,r,key),i=0;
r++;
if(key<a[pos])
for(i=r;i>pos;i--)
a[i]=a[i-1];
else
for(i=r;i>pos+1;i--)
a[i]=a[i-1];
a[i]=key;
return r;
}
@murikadan
Copy link
Author

Give the current array,highest index and new element as input, it returns the new index after inserting the element into the array,
if array is null then highest index is -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment