Searching is a crucial operation in computer science, especially when handling data within arrays. Whether you are trying to locate a specific value or verify its existence, efficient searching algorithms are vital. Today, we're going to explore two popular techniques for searching in arrays: Linear Search and Binary Search.
Linear Search, as the name suggests, is the most straightforward search algorithm. It works by checking each element in the array sequentially until it finds the target value or reaches the end of the array.
Imagine you have an array of integers:
[4, 2, 7, 1, 9, 3]
You are looking for the number 3
. The following steps illustrate how Linear Search would operate on this array:
4
with 3
(no match)2
with 3
(no match)7
with 3
(no match)1
with 3
(no match)9
with 3
(no match)3
with 3
(match found at index 5
)Thus, the Linear Search will return 5
, as the target 3
is located at index 5
.
Binary Search is a more efficient algorithm than Linear Search, but it comes with a caveat: the array must be sorted beforehand. This method works by dividing the search interval in half repeatedly, eliminating half of the elements until the target value is found.
low
and high
.mid = (low + high) / 2
.high = mid - 1
).low = mid + 1
).Consider the sorted array:
[1, 2, 3, 4, 7, 9]
You want to find the number 7
. Here’s how Binary Search works on this array:
low = 0
, high = 5
mid = (0 + 5) / 2 = 2
(value at index 2 is 3
).7
is greater than 3
, narrow to the right half: low = 3
.low = 3
, high = 5
; calculate mid = (3 + 5) / 2 = 4
(value at index 4 is 7
).7
equals 7
, the target is found at index 4
.When deciding whether to use Linear Search or Binary Search, consider the following:
Both searching methods have their advantages, and knowing when to use each can greatly enhance your algorithmic skills!
23/09/2024 | DSA
23/09/2024 | DSA
13/10/2024 | DSA
15/11/2024 | DSA
08/12/2024 | DSA
08/12/2024 | DSA
03/09/2024 | DSA
23/09/2024 | DSA
23/09/2024 | DSA
06/12/2024 | DSA
16/11/2024 | DSA
06/12/2024 | DSA