Linear Search is a searching technique in which we try to search an element either from Starting index to last index or last index to Starting Index and traverse the entire Array.
Here , Array may be either Sorted or not sorted.
Time complicity = O(n).
classMain{publicstaticvoidmain(String[]args){int[]a={4,7,1,5,9,0};intsearchingElement=9;booleanisFound=false;intindexValue=-1;for(inti=0;i<a.length;i++){if(a[i]==searchingElement){isFound=true;indexValue=i;}}if(isFound==true){System.out.println(searchingElement+" is present at index "+indexValue);}else{System.out.println(searchingElement+" is not present in given Array .");}}}
OUTPUT
9 is present at index 4
Binary Search
Binary Search is a searching technique in which we try to search a particular element in a sorted array by repeatedly dividing the search space into two halves.
mid = (start + end)/2;
Here Array must be sorted either increasing or decreasing Order .
// this code for sorted array in increasing Order classMain{publicstaticvoidmain(String[]args){int[]a={1,2,3,4,5,6,7,8,9};intsearchingElement=1;booleanisFound=false;intindexValue=-1;intstartIndex=0;intlastIndex=a.length-1;while(startIndex<=lastIndex){intmid=(startIndex+lastIndex)/2;if(a[mid]==searchingElement){isFound=true;indexValue=mid;break;}elseif(a[mid]<searchingElement){startIndex=mid+1;}else{lastIndex=mid-1;}}if(isFound==true){System.out.println(searchingElement+" is present at index "+indexValue);}else{System.out.println(searchingElement+" is not present in given Array .");}}}
Output
1 is present at index 0
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)