0

LinearSearch

Complete the following linear search method. Find the number num in the array array. Return -1 if the number is not found. You may assume the array is properly ordered. Examples: linearSearch({1,4,7},7) -> 2 linearSearch({2,6,6,8,80},6) -> 2 Read the following incomplete code and fill missing statements to complete the code: public int linearSearch(int[]array, int num) { //TODO Locates a target value in an array / list by examining each element from start to finish -------------------------------------------------------------------------------------------------------------------------- Is this what the question is asking of? public int linearSearch(int[]array, int num) { for(int I = 1; I < array.length; I++) { if(key == array[I]) return I; } return -1; }

21st Mar 2020, 11:51 PM
Cyrus
2 Answers
+ 4
Hello Cyrus You need to start at 0. Otherwise you would miss the first element. What is key? I guess you mean num. The rest of the code is correct. This is how linear search works.
22nd Mar 2020, 12:17 AM
Denise Roßberg
Denise Roßberg - avatar
0
Yes i meant num sorry about that!
22nd Mar 2020, 12:34 AM
Cyrus