This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Do be sure to note the requirement that the array be sorted.
Any specific reason you need to use an array instead of a Collection? [ May 19, 2008: Message edited by: Stevi Deter ]
There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Muhammad Imad Qureshi
Joined: Sep 13, 2005
Thanks for your reply. This is good to know. I don't want to add too many lines of code thats why I am not using collection. here is my code. I would appreciate if you could tell me how can I make it better. this code is based on your suggestion of using binarySearch method of Arrays class.
The problem here is you're going out of your way to sort the array, THEN using a binary search on it. The binary search would be helpful if your array was already sorted but this is going to be slower than just iterating over the array in the first place.
Plus, now this function has a side effect of sorting the array, potentially introducing a subtle bug somewhere else in the program. Some sorting algorithms (quicksort?) may actually have worse performance when trying to sort an already-sorted array.
Anyway, long story short, just iterate over the array .