Thread: Binary search - two functions

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    32

    Binary search - two functions

    Hello,

    I've written two functions doing binary search. This wasn't a homework assignment, I just did that for fun. Which of the two functions do you like more?

    Code:
    int binary_search1(int *arr, int count, int item)
    {
    	int l, r, mid;
    	l = 0; r = count - 1;
    	mid = (r + l) / 2;
    
    	while (l <= r && arr[mid] != item) {
    		if (arr[mid] > item)
    			r = mid - 1;
    		else 
    			l = mid + 1;
                    mid = (r + l) / 2;			
    	}
    	
        if (arr[mid] == item)
    	return mid;
        else
            return -1;
    }
    
    int binary_search2(int *arr, int count, int item)
    {
    	int l, r, mid;
    	l = 0; r = count - 1;
    	
    	while (l <= r) {
    		mid = (r + l) / 2;
    		if (arr[mid] > item)
    			r = mid - 1;
    		else if (arr[mid] < item)
    			l = mid + 1;
                    else
                            return mid;
    	}
    	
        return -1;
    }
    Last edited by kkk; 08-01-2011 at 08:43 AM.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I suggest you read the article I wrote about binary search on my website. In contains code very similar to both of those versions and discusses why they are reasonably inefficient. It then goes on to show the most efficient version.

    In this case your #1 is actually worst because it does 2 item comparisons each time through the loop. The bottom one does 1.5 item comparisons on average. A good version will do exactly 1 item comparison each time through.
    Last edited by iMalc; 08-01-2011 at 01:18 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Difference Between A Linear Search And Binary Search
    By ImBack92 in forum C Programming
    Replies: 4
    Last Post: 05-12-2011, 08:47 AM
  2. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  3. A Binary Search Tree of... Binary Search Trees...
    By SlyMaelstrom in forum C++ Programming
    Replies: 5
    Last Post: 12-10-2005, 02:12 PM
  4. Search Engine - Binary Search Tree
    By Gecko2099 in forum C Programming
    Replies: 9
    Last Post: 04-17-2005, 02:56 PM
  5. binary search and search using binary tree
    By Micko in forum C++ Programming
    Replies: 9
    Last Post: 03-18-2004, 10:18 AM