this is my code
#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;
}
note : there is no compiler error
I think the problem is in the binsearch function or Insertelem function because I tested all other functions and they are working as expected
when I run this code it works so good until the user enter the element he wont and the program just crash
Aucun commentaire:
Enregistrer un commentaire