Searching in Array
Searching in Array
Linear Search
Binary Search
Linear Search:
Linear Search is defined as a sequential search algorithm that starts at one end and goes
through each element of a list until the desired element or group of elements is found.
Otherwise, the search continues till the end of the data set. This has a time complexity
of O(N) where 'N' is the length of the array.
Binary Search:
Binary Search is a searching algorithm used in a sorted array. In this algorithm, the
element is found by repeatedly dividing the search interval in half and deciding the next
interval to find the element. This searching algorithm has a time complexity
of O(log 2 N) where 'N' is the length of the array. The only thing to note is that the
array must be sorted in increasing or decreasing order.
Linear Search
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array,
'val' is the value to search
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit
#include <stdio.h>
if (arr[i] == x)
return i;
return -1;
int main(void)
int x = 10;
// Function call
(result == -1)
return 0;
Output
Present at Index 3
Auxiliary Space: O(1) as except for the variable to iterate through the list, no other
variable is used.
Unsorted Lists: When we have an unsorted array or list, linear search is most
commonly used to find any element in the collection.
Small Data Sets: Linear Search is preferred over binary search when we have small
data sets with
Searching Linked Lists: In linked list implementations, linear search is commonly
used to find elements within the list. Each node is checked sequentially until the
desired element is found.
Simple Implementation: Linear Search is much easier to understand and
implement as compared to Binary Search or Ternary Search.
1/4
How to Implement Binary Search
Algorithm?
The Binary Search Algorithm can be implemented in the
following two ways
Iterative Binary Search Algorithm
Recursive Binary Search Algorithm
Given below are the pseudocodes for the approaches.
Iterative Binary Search Algorithm:
Here we use a while loop to continue the process of
comparing the key and splitting the search space in two
halves.
#include <stdio.h>
3
{
7
10
// Check if x is present at mid
11
if (arr[mid] == x)
12
return mid;
13
14
if (arr[mid] < x)
16
low = mid + 1;
17
18
else
20
high = mid - 1;
21
}
22
23
return -1;
25
}
26
27
// Driver code
28
int main(void)
29
{
30
int x = 10;
33
37
Output
Element is present at index 3
Time Complexity: O(log N)
Auxiliary Space: O(1)
#include <stdio.h>
int largest(int arr[], int n) {
4
int i;
5
max = arr[i];
12
13
return max;
14
}
15
16
int main() {
17
20
printf("%d", largest(arr, n));
21
return 0;
22
Output
9808