Linear/ Sequential
Search
Linear Search and Binary Search
Sequential Search
● A linear search or sequential search is a method for finding an
element within an array.
● It sequentially checks each element of the array until a match is
found or the whole list has been searched.
● The implementation of this algorithm does not require the use of
ordered elements (sorted arrays).
Sequential Search Algorithm
Sequential Search Program
int [ ] N = { 2, 9, 5, 6, 7, 8} // array elements
int x=7; //search value
boolean found=false; //flag
for(int i=0; i<N.length; i++){
if (N[i] == x){
found= true;
System.out.println(N[i]+ “ found at ”+ i);
if (found==false)
System.out.println(x +”not found”);
Binary Search
Binary Search
● Binary search or half-interval search algorithm that finds the
position of a target value within a sorted array.
● It works by comparing the target value to the middle element of
the array.
● If they are unequal, the lower or upper half of the array is
eliminated depending on the result and the search is repeated in
the remaining sub-array until it is successful.
● It only applies to SORTED arrays
Binary Search
Binary Search Algorithm
ARR={12,23,35,46,57,68,70,90}
Input “Enter the Search Value”, VAL if NOT FOUND then
output "NOT FOUND"
LB = 0 end if
FOUND = FALSE
UB = ARR.Length() – 1
loop while LB <= UB AND NOT FOUND
MID = (LB + UB) div 2
if ARR[MID] = VAL then
output MID
FOUND = TRUE
else if ARR[MID] < VAL then
LB = MID + 1
else
UB = MID – 1
end if
end loop
Binary Search Program
int first = 0,
last = arr.length-1,
mid = (first+last)/2;
while( first <= last ){
if ( arr[mid] == key ){
System.out.println("Element found at index:"+ mid);
break;
}
else if ( arr[mid] < key ){
first = mid + 1;
}
else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element not found!");
}