Liner Search - Algorithm
Liner search is an simple and Sequential searching technique. this search, a sequential search where every item is checked and if match is found then it return the element other wise the search continues till the end of the collection i.e size of element.it check all the item one by one.the complexity of liner search is O(n).
Algorithm :
Linear Search (A,x,i,n) Step 1: Set i to 0 Step 2: if i > n then Print Element Not found and Go to step 6 Step 3: if A[i] = x then Print Element is not found and Go to step 6 Step 4: Set i to i + 1 Step 5: Repeat 2,3,4 till n or element not found Step 6: Exit
Example :
public class LinerSrarchExample { private static void search(int[] numberArray,int searchNumber) { int n= numberArray.length; for(int i=0;i<n;i++) { if(i>n) { System.out.println("Element not found."); } if(numberArray[i]==searchNumber) { System.out.println("Element found at "+ i +" Position"); break; } } } public static void main(String[] args) { int[] numberArray = {1,5,8,6,4,8}; int searchNumber = 4; search(numberArray,searchNumber); } }
Comments
Post a Comment