Binary Search Help!

Associate
Joined
1 Mar 2010
Posts
1,389
I am doing a quick exercise for university and I am trying to implement the binary search algorithm to one of my methods.

Code:
	/**
	 * Finds a person within an array of people.
	 */
	public Person find( String name ) 
	{
		for ( Person p : this.members )
		{
			if ( p.getName().equals( name ) )
			{
				return ( p );
			}
		}
	}

This works perfectly fine however when I try my binary search there is clearly something wrong.

Code:
	public Person find( String name ) 
	{
		int min = 0;
		int max = this.members.size() - 1;
		int mid = ( max + min ) / 2;
		
		while ( !( this.members.get( mid ).getName().equals( name ) ) )
		{
			mid = ( max + min ) / 2;
			
			if ( this.members.get( mid ).getName().compareToIgnoreCase( name ) > 0 )
			{
				max = mid - 1;
			}
			else
			{
				min = mid + 1;
			}
		}
		
		return ( this.members.get( mid ) );
	}

Any help is much appreciated, thanks.
 
Last edited:
get(0) should be get(mid) in these if statements, otherwise you're just comparing against the first element in the members list every time.

Code:
if ( this.members.get( 0 ).getName().compareToIgnoreCase( name ) > 0 )
{
	max = mid - 1;
}
else if ( this.members.get( 0 ).getName().compareToIgnoreCase( name ) < 0 )
{
	min = mid + 1;
}
 
get(0) should be get(mid) in these if statements, otherwise you're just comparing against the first element in the members list every time.

Code:
if ( this.members.get( 0 ).getName().compareToIgnoreCase( name ) > 0 )
{
	max = mid - 1;
}
else if ( this.members.get( 0 ).getName().compareToIgnoreCase( name ) < 0 )
{
	min = mid + 1;
}

*facepalm*

I'm embarassed. :p
 
Been there done that, nowt to worry about! I don't dare look out some of the code I wrote for search and sort algorithms at Uni... :)
 
Back
Top Bottom