Created
September 2, 2012 06:11
-
-
Save murikadan/3595271 to your computer and use it in GitHub Desktop.
Inserting an element into a sorted array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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