Skip to content
Advertisement

Method that takes an int array and a value and returns the index of that value in the array

I’ve spent like an hour trying to figure this one out and I couldn’t. This is an exercise for a Java elective course I am taking and I could use some help.

Write a method linearSearch() that takes an array of integers, and an integer value. It should then return the index of the value inside the array (by using a for loop to traverse the elements one by one in order). If the value is not found, -1 should be returned. If more than one value is found, the first occurrence should be returned. Write a program to test your method.

So this is what I tried doing.

JavaScript

But this is obviously wrong. Could you please point me in the right direction? I don’t necessarily want you to give me the answer, just give me an idea about the steps.

Advertisement

Answer

There are several problems.

  • you want to return a value so you need to show that in the method by having a return type of int and not void.

  • you don’t need an index variable, you already have one in your for loop (i) so use that.

  • As you iterate over the loop, as soon as you find the value, just do a return i; to return the index. You do not need any break statements in your method.

  • you don’t need to keep assigning -1 to index so get rid of the else clause (remember you don’t even need index).

  • if you finish the loop the value must not be there so just return -1;.

  • and lastly since you are returning a value, you need to assign it when you call the method. So do int ret = linearSearch(a, 3);. Then print the value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement