Linear and Binary Search
Searching in C
Searching is one of the most common problems in computing.
It is the algorithmic process of finding a particular item in a collection of items.
-
A search typically returns True/False depending on whether the item exists.
-
Sometimes it may also return the location/index of the item.
-
Search operations are usually carried out on a key field.
Consider searching for a value k in an array A of size n.
There are two basic approaches:
-
Sequential (Linear) Search
-
Binary Search
Linear (Sequential) Search
When data items are stored in a list or array, they have a linear/sequential relationship.
-
Each item is stored at a position relative to others.
-
In C arrays, these positions are index values.
-
Since indexes are ordered, we can visit elements one by one in sequence.
Working
-
Start from the first item.
-
Compare each element with the target.
-
Stop when:
-
The element is found, OR
-
All elements are checked.
-
Algorithm: Linear Search
Linear Search (Array A, Value x)
-
Set
i = 0 -
If
i >= n, go to step 7 -
If
A[i] == x, go to step 6 -
Set
i = i + 1 -
Go to step 2
-
Print Element found at index i → go to step 8
-
Print Element not found
-
Exit
C Function (Linear Search)
Linear Search for Sorted Array (Optimized)
Worst-case time complexity: O(N)
Complete Linear Search Program
Example
Array: [23, 34, 41, 65, 70]
Search element: 65
Steps:
-
Compare 23 → not match
-
Compare 34 → not match
-
Compare 41 → not match
-
Compare 65 → match at index 3
Binary Search
Binary search works only on sorted arrays.
Idea
-
Check the middle element.
-
If equal → return index.
-
If key < middle → search left half.
-
If key > middle → search right half.
-
Repeat until found or array exhausted.
Time Complexity: O(log n)
Algorithm: Binary Search
-
Compare key with middle element.
-
If match → return index → stop.
-
If key > middle → search right half.
-
If key < middle → search left half.
-
Repeat until found.
-
If array eliminated → print not found.
-
Stop.
Binary Search Program (Without Function)
Binary Search Using Recursive Function
Iterative Binary Search Function
Binary Search Main Program
Comments
Post a Comment