#include <stdio.h> int binaryFounder(int*,int,int,int,int*);
int main(void) {int ar[100],n,res=-1,i,j,buf,val,arind[100]; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&ar[i]); printf("Enter searching value:"); scanf("%d",&val); for(i=0;i<n;i++) arind[i]=i; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(ar[i]>ar[j]) {buf=ar[i]; ar[i]=ar[j]; ar[j]=buf; buf=arind[i]; arind[i]=arind[j]; arind[j]=buf;} binaryFounder(ar,0,n-1,val,&res); if (res==-1) printf("Not found"); else printf("Found in position %d",arind[res]); return 0;}
int binaryFounder(int ar[],int left,int right,int val,int* res) {int kar=(left+right)/2; if (*res!=-1) return 0; if (left>right) return 0; if (ar[kar]==val) *res=kar; if (ar[kar]<val) binaryFounder(ar,kar+1,right,val,res); if (ar[kar]>val) binaryFounder(ar,left,kar-1,val,res);}
Пример ввода: 5 1 2 3 4 5 4 Пример вывода: Found in position 3 //считаем с 0
#include <stdio.h>
int binaryFounder(int*,int,int,int,int*);
int main(void)
{int ar[100],n,res=-1,i,j,buf,val,arind[100];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&ar[i]);
printf("Enter searching value:");
scanf("%d",&val);
for(i=0;i<n;i++)
arind[i]=i;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(ar[i]>ar[j])
{buf=ar[i];
ar[i]=ar[j];
ar[j]=buf;
buf=arind[i];
arind[i]=arind[j];
arind[j]=buf;}
binaryFounder(ar,0,n-1,val,&res);
if (res==-1)
printf("Not found");
else
printf("Found in position %d",arind[res]);
return 0;}
int binaryFounder(int ar[],int left,int right,int val,int* res)
{int kar=(left+right)/2;
if (*res!=-1)
return 0;
if (left>right)
return 0;
if (ar[kar]==val)
*res=kar;
if (ar[kar]<val)
binaryFounder(ar,kar+1,right,val,res);
if (ar[kar]>val)
binaryFounder(ar,left,kar-1,val,res);}
Пример ввода:
5
1
2
3
4
5
4
Пример вывода:
Found in position 3 //считаем с 0