CC-1 : Implement Linear Search Algorithm.
Description:
Given an input array and an element to be searched, search the required element in the input array using linear search.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Array: 3 , 22 , 14 , 6 , 7 , 90 , 22 , 65 , 39 , |
6 found at index 3 16 found at index -1 |
Pseudocode:
| Integer array named nums and integer named toSearch are received as input parameters. |
| Iterate through using for loop with idx as iteration variable and values of idx ranging from 0 to nums.length:
If nums[idx]=toSearch:
Return idx.
|
| If toSearch is not found return -1. |
Code:
public int linearSearch(int[] nums,int toSearch){
for (int idx=0; idx < nums.length; idx++) {
if (nums[idx]==toSearch) {
return idx;
}
}
return -1;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |