Searching algorithm
Learn basic binary & Sequential searching algorithm
Rifki ahmad fahrezi
Binary search
Binary search is an algorithm that searches through a sorted array. Binary search does not iterate through every element of the array. Instead, it divides the search space in half at each step.
Implementation
Now we're going to implement the binary search algorithm by making a function to do the operation using javascript. Here is the function's code:
Explanation
- Initialize pointers
low
(start of the array)high
(end of the array)
- Loop until
low
exceedshigh
:- Find mid = Math.floor((
low
+high
) / 2) - If
arr[mid] === target
, returnmid
- If
target
is greater thanarr[mid]
, search the right half (low = mid + 1
) - If
target
is smaller thanarr[mid]
, search the left half (high = mid - 1
)
- Find mid = Math.floor((
- Return
-1
if not found.
Sequential search
Sequential (or linear) search is an algorithm that checks each element of an array one by one sequentialy. It is useful for searching in unsorted arrays.
Implementation
Now we're going to implement the Sequential search algorithm by making a function to do the operation using javascript. Here is the function's code:
Explanation
- Define the function: -The function sequentialSearch takes two parameters: an array and a target value.
- Loop through the array:
- Iterate over each element.
- If an element matches the target, return its index.
- Return -1 if the target is not found.
Addition
Binary search is works only for sorted array and fast for larger datasets.
Sequential search is works for any array but slower for large datasets