Welcome, Guest. Please login or register.

Author Topic: Programming question! :)  (Read 9474 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Leffmann

  • Full Member
  • ***
  • Join Date: Feb 2011
  • Posts: 119
    • Show all replies
Re: Programming question! :)
« on: April 17, 2012, 12:26:09 AM »
Don't know about a binary tree, but a binary search will reduce the number of searches to log2 n, i.e. if you have an array of 256 numbers it will do 8 searches. Basic implementation would be:

Code: [Select]
// For an array of 100 numbers, call with binsearch(n, 0, 99);

int binsearch(int n, int a, int b)
{
  if(a == b)
    return a;

  int mid = a + (b-a)/2;
 
  if(n < array[mid])
    return binsearch(n, a, mid);
  else
    return binsearch(n, mid+1, b);
}

EDIT: this binary search assumes the array is sorted in ascending order.
« Last Edit: April 17, 2012, 12:30:41 AM by Leffmann »
 

Offline Leffmann

  • Full Member
  • ***
  • Join Date: Feb 2011
  • Posts: 119
    • Show all replies
Re: Programming question! :)
« Reply #1 on: April 17, 2012, 05:47:59 PM »
Quote from: bloodline;689044
An elegant search algorithm, but unsuitable for my application as I'm not searching for a specific value, but a boundary :)


Actually it's adjusted to do exactly what you want, and can even be optimized further.