5

在一个有序数组中查找具体数字。

 2 years ago
source link: https://blog.51cto.com/u_15797078/5706889
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在一个有序数组中查找具体数字。

精选 原创

Find8 2022-09-23 14:40:49 ©著作权

文章标签 数组 #include 二分查找算法 文章分类 C/C++ 编程语言 阅读数187

要求:查找数组中某一具体数字,并且输出打印其下标。

算法:折算查找算法(二分查找算法)

左下标:int left=0;

右下标:int right=sz-1;

数组中数字个数sz=sizeof(arr)/sizeof(arr[0]);

数组:char arr[]={1,2,3,4,5,6,7,8,9,10};

int med=(right+left)/2;

在一个有序数组中查找具体数字。_二分查找算法
在一个有序数组中查找具体数字。_#include_02
在一个有序数组中查找具体数字。_数组_03
在一个有序数组中查找具体数字。_二分查找算法_04

#include<stdio.h>

int main()

char arr[]={1,2,3,4,5,6,7,8,9,10};

int b=0;

int sz=sizeof(arr)/sizeof(arr[0]);

int left=0;

int right=sz;

printf("请输入要找的数字(1-10以内):");

scanf("%d",&b);

while(left<=right)//保证右大于等于左

int med=(left+right)/2;

if(arr[med]<b)

 left=med+1;

else if(arr[med]>b)//arr[med]代表下标对应的具体数字

 right=med-1;

 printf("已找到,其对应的下标为:%d\n",med);

 break;

if(left>right)

 printf("找不到\n");

return 0;

注:要了解具体的算法,才能写好代码。

  • 1
  • 收藏
  • 评论
  • 分享
  • 举报

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK