Thread: Binary search - two functions

Threaded View

Previous Post Previous Post   Next Post Next Post
  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.

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