其他分享
首页 > 其他分享> > 写一个代码,在arr数组中找到7 分别用循环法和二分法

写一个代码,在arr数组中找到7 分别用循环法和二分法

作者:互联网

循环法

 1 #define _CRT_SECURE_NO_WARNINGS 1
 2 #include<stdio.h>
 3 int main()
 4 {
 5     int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
 6     int k = 6,num,i;
 7     num = sizeof(arr) / sizeof(arr[0]);
 8     for (i = 0; i < num; i++)
 9     {
10         if (arr[i] == 7)
11         {
12             printf("找到了下标=%d", i);
13             break;
14         }
15     }
16     if (i == num)
17         printf("找不到7");
18 }

二分法

 1 #define _CRT_SECURE_NO_WARNINGS 1
 2 #include<stdio.h>
 3 int main()
 4 {
 5     int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
 6     int left = 0, right, sum, mid;
 7     sum = sizeof(arr) / sizeof(arr[0]);
 8     right = sum - 1;
 9     while (left <= right)
10     {
11         mid = (left + right) / 2;
12         if (arr[mid] == 7)
13         {
14             printf("找到了7下标为%d", mid);
15             break;
16         }
17         else if (arr[mid] < 7)
18             left = mid + 1;
19         else
20             right = mid - 1;
21     }
22     if (left > right)
23         printf("找不到7");
24     return 0;
25 }

 

标签:arr,right,循环法,int,二分法,num,printf,sizeof
来源: https://www.cnblogs.com/woheta804983513/p/16527092.html