Look-up tables: finding index of a value below a given number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nigelmercier
    New Member
    • Dec 2009
    • 45

    Look-up tables: finding index of a value below a given number

    Hi guys, I'm a C newbie (a couple of months ago I was a virgin!) working with PIC microcontroller s. I need to do a look-up table to change one value to another, probably best to give an example in pseudocode:

    Code:
    code const integer reading[5] ={12, 96, 147, 245, 747}; // sorted numerically
    code const integer result[5] ={5, 10, 15, 20, 25}; // sorted numerically
    get look-up value for reading[] (for example 120)
    find last value in reading[] below this (for example 96)
    return equivalent value from result[] (for example 10)
    The last part I can deal with, and may not even be required (as you can see, the values in result[] are at intervals of 5, at least for the moment).

    The tables will in reality have up to 100 entries. My plan was to iterate through reading[] and find when the number is bigger, then step back one. Is this OK, or is there a better way? Should I consider hash tables?
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    If values in reading[] are sorted, use binary search.

    Comment

    • nigelmercier
      New Member
      • Dec 2009
      • 45

      #3
      Binary search, you mean keep splitting the array? Can you point me to some code to do this?

      Comment

      • puneetsardana88
        New Member
        • Aug 2009
        • 57

        #4
        Code:
        		 int binarySearch( int [] reading , int target )
        		 {
        		        int found = 0 ;
        			int start=0 , mid =-1 , end = 100 ; 
        				while( !found &&  end >= start )
        			 	 {
        					mid = (start+end) / 2 ;
        					if(reading[mid] == target)
        						found = 1 ;
        					else if (reading[mid] > target) 
        					 	end = mid - 1 ;
        					else
        						start = mid + 1 ;
        			 	}
                                return mid - 1;
         }
        The index you are looking is mid-1.

        Comment

        • nigelmercier
          New Member
          • Dec 2009
          • 45

          #5
          Many thanks, I'll give it a go.

          What a helpful forum this is.

          Comment

          Working...