二分查找法

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>

#include<stdlib.h>







int search(int a[], int n, int num)

{

    int top = 0;

    int bottom = n - 1;

    int half = (top + bottom) / 2;

    while (top <= half)

    {

        printf("这一次查找的数,top=%d,half=%d,bottom=%d\n",top,half,bottom);

        if (a[half] == num)

        {

            return num;//成功找到

        }

        else if (a[half] > num)

        {

            bottom = half - 1;

            half = (top + bottom) / 2;

        }

        else

        {

            top = half + 1;

            half = (top + bottom) / 2;

        }

    }

    return -1;//表示未找到



}



void main()

{

    int num[64];

    time_t tms;

    srand((unsigned int)(time(&tms)));

    for (int i = 0; i < 64; i++)

    {

        num[i] = rand() % 100;

        //printf("%d\n", num[i]);

    }

    for (int i = 0; i < 64 - 1; i++)//为随机生成的数组排序

    {

        for (int j = 0; j < 64 - 1 - i; j++)

        {

            if (num[j]>num[j + 1])

            {

                int tmp = num[j];

                num[j] = num[j + 1];

                num[j + 1] = tmp;

            }

        }

    }

    for (int i = 0; i < 64; i++)//打印出排序后的数组

    {

        printf("%d\n", num[i]);

    }





    int x = 0;

    scanf("%d", &x);

    int result = search(num, 64, x);

    if (result == -1)

    {

        printf("\n未找到%d", x);

    }

    else

    {

        printf("找到了%d", x);

    }

    system("pause");



}

代码很简单,下面就说下思路吧。。。

首先就是先生成一组随机数,然后用冒泡排序将数组排序

然后每次比较中间的数和要查找的数,要查的数大,那就在下面那一坨里找,反之同理

恩,也没啥要说的了,这个确实太简单了,思路一般小学生就能掌握了。。。。

你可能感兴趣的:(二分查找)