0

So I have written the following program with methods: inputArray, selectionSort, binarySearch, and printArray. I am currently working on the main method and am struggling with what to do.

"Write the main method to invoke inputArray, selectionSort, and printArray methods. Next, your main method should ask the user to input a double value to use as a search key and then invoke the binarySearch method. Finally, the main method should print out the location of the key if it is in the list and an appropriate message if the key is not in the list."

How can I print the the index value from the binary search?

7
  • 3
    ask the precise problem you face. Commented Apr 18, 2016 at 20:58
  • @RamanShrivastava I am currently trying to do the following: "Finally, the main method should print out the location of the key if it is in the list and an appropriate message if the key is not in the list." Commented Apr 18, 2016 at 21:00
  • 2
    What does binarySearch return if the key is not found? Therein is the answer. Commented Apr 18, 2016 at 21:00
  • 1
    Hint: Try starting with int found = binarySearch(array1, key); Commented Apr 18, 2016 at 21:01
  • D E B U G. Answer lies there. Commented Apr 18, 2016 at 21:01

1 Answer 1

1

You need to use the return value of the binary search method:

if (binarySearch(array1, key) < 0) {
    // key is not in the array
} else {
    // key is in the array
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. I definitely should've been able to think about that lol. My brain is getting fried. Now I am stuck on printing out where the key variable lies in the array. I tried System.out.print("The key is located at " + array1[key] + " in the array."); but it didn't like that. I don't think array1[key] is legal. Could you give me a hint?
@BronsonLane see cricket_007's comment to your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.