Searching
Searching
by
Farhan Sufyan
Contents
1 Searching 1
1.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Linear or Sequential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.1 How to Implement Binary Search Algorithm? . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Sample Question . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Chapter 1
Searching
1.1 Searching
• Searching is an operation or a technique that helps finds the place of a given element or value from any data
structure where it is stored.
• Some of the standard searching technique that is being followed in the data structure:
1
1.2 Linear or Sequential Search
• Linear or sequential search is made over all the elements one by one. In other words, the list or array is
traversed sequentially and every element is checked.
• Working of Linear Search: Every element is checked one by one from the starting and
– If a match is found then that particular item location/position is returned
– Otherwise the search continues till the end of the data collection.
• Now, start from the first element and compare K with each element of the array.
• The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element. And
follow the same process until the respective element is found.
2
• Let us look at the step-by-step searching of the key element (say 47) in an array using the linear search
method.
3
• Time Complexity of Linear Search:
– Best Case: In the best case, the key might be present at the first index. So the best case complexity is
O(1).
– Worst Case: In the worst case, the key might be present at the last index i.e., opposite to the end from
which the search has started in the list. So the worst-case complexity is O(N) where N is the size of the
list.
– Average Case: O(N)
• Auxiliary Space: O(1) as except for the variable to iterate through the list, no other variable is used.
– Linear search can be used irrespective of whether the array is sorted or not. It can be used on arrays of
any data type.
– Does not require any additional memory.
– It is a well-suited algorithm for small datasets.
4
{Linear Search (Array A, Value x)}
Step 1: Set i to 1
Step 2: if $i > n$ then go to step 7
Step 3: if $A[i] = x$ then go to step 6
Step 4: Set $i$ to $i + 1$
Step 5: Go to Step 2
Step 6: Print Element $x$ Found at index $i$ and go to step 8
Step 7: Print element not found
Step 8: Exit
// Driver code
int main (void) {
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, N, x);
if (result == -1){
printf("Element is not present in array")
}
else{
printf("Element is present at index %d", result);
}
return 0;
}
5
1.3 Binary Search
• Binary search is a very fast and efficient searching technique.
• In binary search, we basically ignore half of the elements just after one comparison.
• Time Complexity:
6
• Applications of Binary Search Algorithm:
– Binary search can be used as a building block for more complex algorithms used in machine learning,
such as algorithms for training neural networks or finding the optimal hyperparameters for a model.
– It can be used for searching in computer graphics such as algorithms for ray tracing or texture mapping.
– It can be used for searching a database.
• Advantages of Binary Search:
– Binary search is faster than linear search, especially for large arrays.
– More efficient than other searching algorithms with a similar time complexity, such as interpolation
search or exponential search.
– Binary search is well-suited for searching large datasets that are stored in external memory, such as on
a hard drive or in the cloud.
Disadvantages of Binary Search:
7
• The following is our sorted array and let us assume that we need to search the location of value 31 using
binary search.
• First, we shall determine half of the array by using this formula -
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
• Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value
at location 4 is 27, which is not a match.
• As the value is greater than 27 and we have a sorted array, so we also know that the target value must be in
the upper portion of the array.
• We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high − low)/2
• Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
• The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the value
must be in the lower part from this location.
8
• We compare the value stored at location 5 with our target value. We find that it is a match.
9
Example
• Consider an array arr[] = 2, 5, 8, 12, 16, 23, 38, 56, 72, 91, and the target = 23.
10
• In the above exqmple, we are using
mid = low + (high − low)/2
• But, why we are calculating the middle index this way, we can simply add the lower and higher index and
divide it by 2.
mid = (low + high)/2
• It fails for larger values of int variables low and high. Specifically, it fails if the sum of low and high is greater
than the maximum positive int value (231 − 1).
11
• C program to implement iterative Binary Search
#include <stdio.h>
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present"
" in array")
: printf("Element is present at "
"index %d",
result);
return 0;
}
12
• C program to implement recursive Binary Search
#include <stdio.h>
// A recursive binary search function. It returns location of x in given array
arr[low.....high] is present, otherwise -1
// Driver code
int main()
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
13
1.4 Sample Question
• Explain the Binary Search Algorithm and its steps.
• Compare and contrast linear search and binary search algorithms. How do their efficiencies differ?
• Write a recursive binary search function in a programming language of your choice.
• What are the key differences between binary search and linear search? Explain with examples.
• Use binary search to find the value 40 in the sorted array: [11, 22, 30, 33, 40, 44, 55, 60, 66, 77, 80, 88, 99].
• Analyze the time complexity of binary search and explain why it is more efficient than linear search for large
datasets.
• Write a C program to implement linear search.
• Write a C program to implement binary search.
14