6.3.5 Linear Search You often need to search for the position of a specific elem
ID: 3821604 • Letter: 6
Question
6.3.5 Linear Search You often need to search for the position of a specific element in an array so that you can or it. Visit have a or you have come to the end of the array. Here we search for the position of the first element in an array that is equal to 100: int searchedValue 100 int pos 0; boolean found false while (pos values.length && !found) if (values [pos] searched Value) found true else pos++ if (found) f System.out.println("Found at position pos); else System.out.println("Not found"); This algorithm is called linear search or sequential search because you inspect the elements in sequence. If the array is sorted, you can use the more efficient binary search algorithm see Special Topic 6.2 on page 2Explanation / Answer
In this linear search we are searching posiion of the specific item.
We initialized boolean found = false; , because at starting we are assuming tha we did not found item.
While loop, we will continue run untill end of values(pos<values.length) and item is not found(!found), if one of the condition is false, then we will stop while loop, it means either we found the item or we reached to end of values.
Inside while loop we are checking item in values at current position,if item is matches the we are making found = true , othewise found will be false as we initialized.
At end outside of loop we are checking , if found = ture(if(found)) then Item is found else not found.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.