Pseudocode Examples of Basic Search Algorithms
Here are the pseudocode examples for the two most fundamental array search algorithms: Linear Search and Binary Search.
1. Linear Search Pseudocode
Linear search checks each element one by one from the beginning to the end of the collection.
Function LinearSearch(array, target):
// Loop through every element in the array
For i from 0 to length(array) - 1:
// Check if the current element matches the target
If array[i] == target Then
Return i // Return the index where the target was found
End If
End For
// If the loop finishes without finding the target, return -1 (not found)
Return -1
End Function
2. Binary Search Pseudocode
Binary search requires a sorted array. It repeatedly divides the search interval in half.
Function BinarySearch(sortedArray, target):
left = 0
right = length(sortedArray) - 1
While left <= right:
// Find the middle index
mid = left + floor((right - left) / 2)
// Check if target is present at mid
If sortedArray[mid] == target Then
Return mid
// If target is greater, ignore the left half
Else If sortedArray[mid] < target Then
left = mid + 1
// If target is smaller, ignore the right half
Else
right = mid - 1
End If
End While
// Target was not present in the array
Return -1
End Function
Comments
Post a Comment