• Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary search of float array  RSS feed

 
Scott Halepaska
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doing an early exercise out of the Java Examples in a Nutshell book and they are asking for 'an efficient search algorithm to find the desired position' of two floats in a sorted array that bound an int. My try is below:



This is working for the example but I would like to know if it is considered 'efficient' or even good?
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you trying to find the index of the element that matches searchnum? What do you want to return if searchnum doesn't exist in the array? It looks to me that with line 6 and 7, if searchnum falls between the elements at indexes n and n+1, you return n. Is that what you want? What happens if the searchnum you pass in is less than the element at index 0, or greater then the element at index length-1?

It's anticipating and testing for exceptional cases like these that makes your programs resilient, plus it's sort of fun too! It's like a brain teaser or other puzzle, and if you don't love puzzles, you probably won't enjoy programing!
 
Scott Halepaska
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Charles wrote:Are you trying to find the index of the element that matches searchnum? What do you want to return if searchnum doesn't exist in the array? It looks to me that with line 6 and 7, if searchnum falls between the elements at indexes n and n+1, you return n. Is that what you want? What happens if the searchnum you pass in is less than the element at index 0, or greater then the element at index length-1?


The exercise was to produce a random float[] and then print the floats that border a user inputted int. It works as expected and it could surely be hardened as you mention for better tests. Really just wondering if it is decent implementation. Is it feasible that an int would ever equal a random float? Might have to deal with that also. Thanks for your time.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!