M Tahir Aslam FA20-CVE-071 Itcp Assaighment 2: Linear Search
M Tahir Aslam FA20-CVE-071 Itcp Assaighment 2: Linear Search
FA20-CVE-071
ITCP
ASSAIGHMENT 2
SEARCHING ALGORITHMS:
Searching Algorithms are designed to check for an element or retrieve an element from any data
structure where it is stored. Based on the type of search operation, these algorithms are generally
classified into two categories:
1. Sequential Search: In this, the list or array is traversed sequentially and every
element is checked. For example: Linear Search.
2. Interval Search: These algorithms are specifically designed for searching in sorted
data-structures. These type of searching algorithms are much more efficient than
Linear Search as they repeatedly target the center of the search structure and divide
the search space in half. For Example: Binary Search.
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search an element
or value in a given array by traversing the array from the starting, till the desired element or
value is found.
It compares the element to be searched with all the elements present in the array and when the
element is matched successfully, it returns the index of the element in the array, else it return -1.
Linear Search is applied on unsorted or unordered lists, when there are fewer elements in a list.
Features of Linear Search Algorithm
2. It has a time complexity of O(n), which means the time is linearly dependent on the
number of elements, which is not bad, but not that good too.
Binary Search
Binary Search is used with sorted array or list. In binary search, we follow the following steps:
1. We start by comparing the element to be searched with the element in the middle of the
list/array.
3. If we do not get a match, we check whether the element to be searched is less or greater
than in value than the middle element.
4. If the element/number to be searched is greater in value than the middle number, then we
pick the elements on the right side of the middle element(as the list/array is sorted, hence
on the right, we will have all the numbers greater than the middle number), and start
again from the step 1.
5. If the element/number to be searched is lesser in value than the middle number, then we
pick the elements on the left side of the middle element, and start again from the step 1.
Binary Search is useful when there are large number of elements in an array and they are sorted.
So a necessary condition for Binary search to work is that the list/array should be sorted.
2. It has a time complexity of O(log n) which is a very good time complexity. We will
discuss this in details in the Binary Search tutorial.
3. It has a simple implementation.