Thread: please help me with logic

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    347

    please help me with logic

    I was trying to solve the following problem for a very long time but not getting the logic of how to solve the problem.
    Code:
    int binsearch(int x, int v[], int n)
    {
    int low, high, mid;
    low = 0;
    high = n - 1;
    while (low <= high) 
    {
    mid = (low+high)/2;
    if (x < v[mid])
    high = mid + 1;
    else if (x > v[mid])
    low = mid + 1;
    else /* found match */
    return mid;
    }
    return -1; /* no match */
    }
    The binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside.) Write a version with only one test inside the loop and measure the difference in run-time? Please suggest me the logic.

  2. #2
    Registered User
    Join Date
    May 2013
    Posts
    228
    To my best understanding, you could drop the second comparison inside the loop, and test for equality against v[mid] outside the loop.
    This should take you from 3log(n) comparisons to 2log(n)+1.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with logic !
    By noririco in forum C Programming
    Replies: 16
    Last Post: 12-03-2013, 12:20 PM
  2. Help with logic..
    By bconnor in forum C Programming
    Replies: 1
    Last Post: 05-18-2006, 07:49 PM
  3. Logic?
    By Kurious in forum C++ Programming
    Replies: 3
    Last Post: 01-31-2003, 07:36 PM
  4. help with logic please
    By Tryin in forum C Programming
    Replies: 7
    Last Post: 01-28-2003, 02:54 AM
  5. Logic?
    By planet_abhi in forum Game Programming
    Replies: 1
    Last Post: 01-18-2003, 03:46 PM