Click here to Skip to main content
15,889,595 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi i am implementing binary search in c#, here is the code

C#
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]);
    }


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?
Posted
Comments
Sergey Alexandrovich Kryukov 29-Sep-14 1:45am    
Always use the debugger, you will see what's going on.
—SA

Try removing equal from
C#
while(max>=min)

So change
C#
while(max>=min)
to
C#
while(max>min)
 
Share this answer
 
Comments
suleman115 29-Sep-14 1:31am    
well i mentioned in the question that when i remove =, program works fine, but we need = to check for the values at index 0 and 6 that is min and max..then what?
gopesh2010 29-Sep-14 1:40am    
First of all if max is equal to min it will always go to infinite loop, secondly before going inside your loop you can check that the value you are going to search is at location min or max, that will save the overhead of a loop.
suleman115 29-Sep-14 1:54am    
got the point about min=max, thank you
I should just make the min=max+1 when i find target, here:

C#
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;
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900