Algorithm BinarySearch
Input: Array of integers array[], number of elements n, search key search
Output: Position of the search key in the array
Output "Enter number of elements"
Read n
Output "Enter", n, "integers"
For c = 0 to n - 1
Read array[c]
End For
Output "Enter value to find"
Read search
p = BinarySearch(array, 0, n, search)
If p == -1
Output "Element not found"
Else
Output search, "position element found at position", p
End If
Return 0
End Algorithm
// Function to perform binary search
Algorithm BinarySearch(array, first, last, search)
Input: Array of integers array[], first and last indices, search key search
Output: Position of the search key in the array
last = last - 1
While first <= last
middle = (first + last) / 2
If array[middle] < search
first = middle + 1
Else If array[middle] > search
last = middle - 1
Else
Return middle
End If
End While
Return -1 // No match
End Algorithm
Algorithm LinearSearch
Input: Array array[], Size n, Integer search
Output: Print the location of search if found, else print a message
Output "Enter number of elements in array"
Read n
Output "Enter", n, "integer(s)"
For c = 0 to n - 1
Read array[c]
End For
Output "Enter a number to search"
Read search
For c = 0 to n - 1
If array[c] = search
Output search, "is present at location", c + 1
Break
End If
End For
If c = n
Output search, "isn't present in the array"
Return 0
End If
End Algorithm