本文介绍了C#中的二进制搜索进入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在c#中实现二进制搜索,这里是代码



Hi i am implementing binary search in c#, here is the code

int[] a={1,3,4,5,7,9,10};
int max=6;
int min=0;
int target=1;
while(max>=min)
{
    if((max+min)!=0)
    {
    int mid=(max+min)/2;
    if(a[mid]==target)
    {
        Console.Write(a[mid]);
        min=max;
    }
        else if(a[mid]>target)
        max=mid-1;
        else
        min=mid+1;
    }
    else
    Console.Write(a[max]);
    }





但它是无限循环,如果我删除= in(max> = min)但它不会检查起始最小值和最大值,尽管如果我将目标设置为除了极值之外的任何值,它会给出真实的结果。我该怎么办?



but it is going in infinite loop, the code works fine if I remov = in while(max>=min) but it won't check for starting min and max value although if I set target equal to anything anything but extreme values, it gives true result. what can I do?

推荐答案

while(max>=min)



因此更改


So change

while(max>=min)

while(max>min)


int[] a={1,3,4,5,7,9,10};
int max=6;
int min=0;
int target=1;
while(max>=min)
{
    int mid=(max+min)/2;
    if(a[mid]==target)
    {
        Console.Write(a[mid]);
        min=max+1;
    }
        else if(a[mid]>target)
        max=mid-1;
        else
        min=mid+1;
    }


这篇关于C#中的二进制搜索进入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:39