二分查找的五种实现

// 二分查找的几种循环实现

#include 
#include 

// while循环
void fun1(int num)
{
    int a[1024];
    for (int i = 0; i < 1024; i++)
    {
        a[i] = i;
    }
    int shang=0;
    int xia=1024-1;
    int zhong;
    while (shang2;
        printf("shang=%d,zhong=%d,xia=%d\n", shang, zhong, xia);
        if (zhong==num)
        {
            printf("找到了..\n");
            break;
        }
        else if (zhong1;
        }
        else
        {
            xia = zhong - 1;
        }
    }
}

// for循环
void fun2(int num)
{
    int a[1024];
    for (int i = 0; i < 1024; i++)
    {
        a[i] = i;
    }
    int shang = 0;
    int xia = 1024 - 1;
    int zhong = (shang + xia) / 2;
    for (;shangprintf("shang=%d,zhong=%d,xia=%d\n", shang, zhong, xia);
        if (zhong == num)
        {
            printf("找到了..\n");
            break;
        }
        else if (zhong < num)
        {
            shang = zhong + 1;
        }
        else
        {
            xia = zhong - 1;
        }
        zhong = (shang + xia) / 2;
    }
}

// do..while循环
void fun3(int num)
{
    int a[1024];
    for (int i = 0; i < 1024; i++)
    {
        a[i] = i;
    }
    int shang = 0;
    int xia = 1024 - 1;
    int zhong;
    do
    {
        zhong = (shang + xia) / 2;
        printf("shang=%d,zhong=%d,xia=%d\n", shang, zhong, xia);
        if (zhong == num)
        {
            printf("找到了..\n");
            break;
        }
        else if (zhong < num)
        {
            shang = zhong + 1;
        }
        else
        {
            xia = zhong - 1;
        }
    } while (shanggoto循环
void fun4(int num)
{
    int a[1024];
    for (int i = 0; i < 1024; i++)
    {
        a[i] = i;
    }
    int shang = 0;
    int xia = 1024 - 1;
AAA:    int zhong = (shang + xia) / 2;
    printf("shang=%d,zhong=%d,xia=%d\n", shang, zhong, xia);
    if (zhong == num)
    {
        printf("找到了..\n");
    }
    else if (zhong < num)
    {
        shang = zhong + 1;
        goto AAA;
    }
    else
    {
        xia = zhong - 1;
        goto AAA;
    }
}

// 递归
int FindNum(int a[],int shang,int xia, int num)
{
    int zhong = (shang + xia) / 2;
    printf("shang=%d,zhong=%d,xia=%d\n", shang, zhong, xia);
    if (zhong == num)
    {
        printf("找到了..\n");
    }
    else if (zhong < num)
    {
        shang = zhong + 1;
        return FindNum(a, shang, xia, num);
    }
    else
    {
        xia = zhong - 1;
        return FindNum(a, shang, xia, num);
    }
}
void fun5(int num)
{
    int a[1024];
    for (int i = 0; i < 1024; i++)
    {
        a[i] = i;
    }
    int shang = 0;
    int xia = 1024 - 1;
    FindNum(a,shang,xia,num);

}

int main()
{
    fun1(333);
    printf("\n");
    fun2(333);
    printf("\n");
    fun3(333);
    printf("\n");
    fun4(333);
    printf("\n");
    fun5(333);
    system("pause");
    return 0;
}

你可能感兴趣的:(算法)