Searching in Data Structure -Linear Search and Binary search. Detail PPT File completing all basics with time complexity and with advantage and disadvantage
3. Linear search
In linear search, we compare every elements of the array one by one in a sequential
manner until a match is found
4. Linear search algorithm
Linear_search(A[], n, e)
Step 1) Set i = 0 and loc = 0.
Step 2) repeat steps 3, 4 while(loc=0 && i<n)
Step 3) if A[i] = e, then set loc = i;
Step 4) Set i = i+1
Step 5) If loc = 0 , then, element ‘e’ is not in array
Step 6) else return i (location of e).
Here, A= name of array
n= size of array A
i= used for index of array
e= element to be searched
loc= this will store the location of searched element
Complexity = O(n)
5. Advantages & Disadvantages
Advantages:
We can apply for both sorted and unsorted data.
Best case running time complexity is O(1)
Disadvantages:
Worst case Running Time complexity is O(n)
5
6. Binary search
Here, we compare search elements ‘e’ with the middle element of array A,
that is A[mid], where mid = n/2. and n = size of array.
In binary search array elements must be sorted (either in ascending or
descending order)
If e = A[mid] we have found element
If e < A[mid] restrict search to A[0] to A[m-1]
If e > A[mid] restrict search to A[m+1] to A[n-1]
7. Algorithm of binary search
Binary_search(A[], n, e)
Step 1) set low = 0, high = n-1
Step 2) repeat steps 3 and 4 while(low<=high)
Step 3) mid = (low + high)/2
Step 4) if (e == A[mid])
Return mid
Else if (e< A[mid])
High = mid – 1
Else low = mid + 1
Step 5) return -1
Here, low = lower bound of array A of size n
high = upper bound of array A
e= element to be searched
::Complexity = O(log n)
8. Advantages & Disadvantages
Advantages
Worst case running time complexity is O(logn).
Perform better than linear search
Disadvatages
We can use only for the sorted data.
8