50个[100,300]的随机数,要求用二分法查找从键盘录入的关键数字。找到回复位置,找不到回复不存在(C语言)

2019

50个[100,300]的随机数,要求用二分法查找从键盘录入的关键数字。找到回复位置,找不到回复不存在

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 
 5 void sort(int arr[])
 6 {
 7     int t;
 8     int i = 0, j = 0;
 9     for(i=0; i<49; i++)
10         for(j=i+1; j<50; j++)
11         {
12             if(arr[i]>arr[j])
13             {
14                 t = arr[i];
15                 arr[i] = arr[j];
16                 arr[j] = t;
17             }
18         }
19 }
20 void BinarySearch(int arr[], int t)
21 {
22     int mid, low, high;
23     low = 0;
24     high = 50;
25     while (low <= high)
26     {
27         mid = (low+high)/2;
28         if (arr[mid] == t)    break;
29         else if(arr[mid] < t)    low = mid+1;
30         else high = mid-1;
31     }
32     if (low <= high)
33         printf("要查询的值%d在第%d个位置", t, mid+1);
34     else
35         printf("该值不存在");
36 }
37 
38 int main()
39 {
40     int i, a, t;
41     srand((unsigned)time(NULL));
42     int arr[50];    //50个随机数
43     for (i=0; i<50; i++)
44     {
45         a = rand()%201+100;    //50个100-300的随机数
46         arr[i] = a;
47     }
48     sort(arr);    //先对随机数从小到大排序 
49     for(i=0; i<50; i++)
50     {
51         printf("%d ", arr[i]);
52     }
53     printf("\n");
54     printf("请输入要查询的值:"); 
55     scanf("%d", &t);
56     BinarySearch(arr, t);
57 }

 

posted @ 2020-12-10 21:16  郑NINE  阅读(560)  评论(0编辑  收藏  举报