引言:c语言编程基础算法,查找顺序链表或数组某个元素下标的常用方法
核心思想:求数组元素个数的方法、指针运算、向前向后同时遍历。
程序如下:
#define _CRT_SECURE_NO_WARNINGS 1//避免scanf函数报错
#include <stdio.h>
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9,10};
int k;
int left=0;
int right= 0;
int mid=0;
int sz=0;
printf("Please enter the number you are looking for\n");
scanf("%d",&k);
sz=sizeof(arr)/sizeof(arr[0]);
left=0;
right=sz-1;
while(left<=right)
{
mid=(left+right)/2;
if(arr[mid]<k)
left=mid+1;
else if(arr[mid]>k)
right=mid-1;
else
{
printf("We found that the subscript of this number is %d\n",mid);
break;
}
}
if(left>right)
printf("sorry we can't fund the subscript");
return 0;
}
运行并验证: