Lab2

1. Write an iterative program to search for an element in an array using

a. Linear search

b. Binary search

Pseudocode for Linear search

Algorithm linearsearch (A, n, e)

Input Array A of n integers and search element e

Output The position of element e in the array if the element is present in the array; 0 otherwise return -1

i ← 0

while i <n do

if A[i] = e then

return i

i←i+1

return -1

Pseudocode for Binary search

Algorithm binarysearch (A, low, high, e)

Input Array A of n integers and search element e

Output The position of element e in the array if the element is present in the array; 0 otherwise return -1

while low ≤ high do

mid ← (low + high)/2

if A[mid] > e then

high ← high – 1

else if A[mid] < e then

mid ← mid + 1

else

return mid

return -1