View Single Post
Old 03-18-2012, 06:52 PM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,635
Thanks: 4
Thanked 2,448 Times in 2,417 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Looks alright to me; you'll never get to the else condition though. The search entry will always be <, = or > the current iteration, regardless of if it exists in the list.
If you make it through the list without a result, then you have no entry found.

Code:
			int low = 0;
			int high = studentArray.length - 1;
		
			Student result = null;
			while(high >= low)
			{
				int mid = (low+high)/2;
				if(searchEntry.compareToIgnoreCase(studentArray[mid].getLastName()) < 0)
				{
					high = mid - 1;

				}
				else if(searchEntry.compareToIgnoreCase(studentArray[mid].getLastName()) > 0)
				{
					low = mid + 1;
				}
				else if(searchEntry.compareToIgnoreCase(studentArray[mid].getLastName()) == 0)
				{
					result = studentArray[mid];
					high = -1;
				}
			}
			if (result != null)
			{
				System.out.println("Student found: " + result);
			}
			else
			{
				System.out.println("No student with last name: " + searchEntry);
			}
The algorithm is otherwise correct.
Fou-Lu is offline   Reply With Quote