这是我的代码
<小时/>#include <stdio.h>
void show(int*,int);
int sort (int*,int);
int BinSearch(int[],int,int);
int Insertelem(int*,int,int,int*);
int main(void)
{
int array[100]={15,30,40,10,25,5,35,20,45};
int len=9;//length
int *pos=0;//position
int elem=0;//element
int ok=0;
printf("array : ");
show(array,len);
sort(array,len);
printf("array after sorting : ");
show(array,len);
printf("enter the number you want to add :");
scanf("%d",&elem);
*pos=BinSearch(array,elem,len);
ok=Insertelem(array,len,elem,pos);
show(array,len);
return 0;
}
void show(int *array,int len)//print the array
{
for(int i=0;i<len;i++)
{
printf("%d,",array[i]);
}
printf("\n");
}
int sort(int *array,int len)//sort the array
{
int help=0;
for(int i=len-1;i>0;i--)
{
for(int j=0;j<i;j++)
{
if(array[j]>array[j+1])
{
help=array[j];
array[j]=array[j+1];
array[j+1]=help;
}
}
}
return *array;
}
int BinSearch(int array[100],int elem,int len)//searching for the position
{
int first=1;
int last=len-1;
int middle=(first+last)/2;
int pos;
while(first<=last)
{
if(elem<array[middle])
{
last=middle-1;
middle=(first+last)/2;
}
else if(elem>array[middle])
{
first=middle+1;
middle=(first+last)/2;
}
else if(elem==array[middle])
{
break;
}
}
pos=array[middle]+1;
return pos;
}
int Insertelem(int *array,int len,int elem,int *pos)//inserting the element
//in the right position
{
len++;
for(int i=len-1;i>*pos+1;i--)
{
array[i+1]=array[i];
}
elem=array[*pos];
return *array;
}
<小时/>
注意:没有编译器错误
<小时/>我认为问题出在 binsearch 函数或 Insertelem 函数中,因为我测试了所有其他函数并且它们按预期工作
<小时/>当我运行这段代码时,它工作得很好,直到用户输入他不会输入的元素并且程序崩溃了
最佳答案
int pos=-1;//change not pointer
...
pos=BinSearch(array,elem,len);
ok=Insertelem(array,len,elem,&pos);//pos is no need for a pointer, because since not changed.
len += 1;//The length must be changed(or by inside Insertelem)
...
int BinSearch(int array[100],int elem,int len)//searching for the position
{
int first=0;//not 1
...
pos=first;//not midlle, not element of array(array[middle])
return pos;
}
int Insertelem(int *array,int len,int elem,int *pos)
{
...
for(int i=len-1;i>= *pos;i--)//not i>*pos+1
...
array[*pos]=elem;//not elem=array[*pos];
return *array;//??
}
关于c - 使用二分搜索在排序数组的正确位置插入一个元素以找到正确的位置,但是出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565420/