DSA Lab 6
DSA Lab 6
SEARCHING TECHNIQUES
USING PYTHON
MARKS AWARDED:
OBJECTIVES:
Implementing linear search technique, Binary search technique.
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.
• 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.
#Function Declared:
def linear_search(mylist,find,start,length):
if start<length:
if mylist[start]==find:
print(“The element found at”, start+1,”position”)
else:
linear_search(mylist,find,start+1,length)
else:
print("Element not found")
#DriverCode:
Final Thoughts
You may like linear search because it is so simple to implement, but it is not used
practically because binary search is a lot faster than linear search.
TASK: Given a list of n elements and search a given element x in the list using linear search.
a. Start from the leftmost element of list a [ ] and one by one compare x with each
element of list a[ ].
b. If x matches with an element, return the index.
c. If x doesn’t match with any of elements, return ("Element not found").
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. If we get a match, we return the index of the middle element.
3. 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.
4. 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.
5. Binary Search is useful when there are large number of elements in an array and they
are sorted.
6. So a necessary condition for Binary search to work is that the list/array should be sorted.
def binary_search(mylist,find_this,start,end):
if start<=end:
mid=(start+end)//2
if mylist[mid]==find_this:
print("The element found at",mid+1,"position")
else:
if mylist[mid]>find_this:
binary_search(mylist,find_this,start,mid-1)
else:
binary_search(mylist,find_this,mid+1,end)
else:
print("Element not found")
print("Enter list:")
mylist=[int(b) for b in input().split()]
list.sort(mylist)
print("the sorted list is",mylist)
find_this=eval(input("Enter the search element:"))
end=len(mylist)
start=0
binary_search(mylist,find_this,start,end)
a. Search a sorted list by repeatedly dividing the search interval in half. Begin with an
interval covering the whole list.
b. If the search key is less than the item in the middle item, then narrow the interval to
the lower half. Otherwise narrow it to the upper half.
c. Repeat the procedure until the value is found or the interval is empty. Consider a
sorted list a [ ] with 9 elements and the search key is 31.
How it works? The following steps are followed to find the number at a certain index:
3. Again low = mid +1 = 1 +1 =2, high = 3, mid = (2 + 3) /2 = 2a[mid] = a[2] = 31 which is the search
So the search is successful.
Algorithm:
Let the searched element be x.
The idea is to first find the smallest Fibonacci number that is greater than or equal to the
length of given array. Let the found Fibonacci number be fib (m’th Fibonacci number). We
use (m-
2) ’th Fibonacci number as the index (If it is a valid index). Let (m-2)’th Fibonacci Number
be i, we compare arr[i] with x, if x is same, we return i. Else if x is greater, we recur for sub-
array after i, else we recur for subarray before i.
1. Let arr [0 ….. n-1] be the input array and element to be searched be x.
2. Find the smallest Fibonacci Number greater than or equal to n. Let this number be
fibM [m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be
fibMm1
[(m1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].
c. Else If x is less than the element, move the three Fibonacci variables two
Fibonacci down, indicating elimination of approximately rear two-third of the
remaining array.
d. Else x is greater than the element, move the three Fibonacci variables one
Fibonacci down. Reset offset to index. Together these indicate elimination of
approximately front one-third of the remaining array.
4. Since there might be a single element remaining for comparison, check if fibMm1 is 1.
If Yes, compare x with that remaining element. If match, return index.
LAB ASSIGNMENT:
1. A person has registered for voter id, he received a voter number and he need to check
whether it exist in the voter or not. Use a binary searching in a recursive way to find
whether the voter number exist in the list or not, taking an array of size 8.
2. Use linear search technique to search for a key value in a given list of characters and
print the message found or not, taking an array of size 8.
a) Find the time complexity of linear search?
……………………………………………………………………………………….
b) Find the time complexity of binary search?
……………………………………………………………………………………….
Lab Report:
(It is recommended to write Lab Report in bullet Form)
Method: Lab reports and instructor observation during Lab sessions Outcome
Assessed:
a. Ability to conduct experiments, as well as to analyze and interpret data (P3/PLO 4).
b. Ability to function on multi-disciplinary teams (A/PLO 9).
c. Ability to use the techniques, skills, and modern engineering tools necessary for engineering
practice (P/PLO 5).
d. An ability to design a solution for an open-ended lab with appropriate considerations for public health
and safety, cultural, societal, and environmental factors. (C/PLO3)
Performance Exceeds expectation (5-4) Meets expectation (3-2) Does not meet expectation Marks
(1-0)
1. Realization of Selects relevant equipment to the Needs guidance to select relevant Incapable of selecting relevant
Experiment [a, c] experiment, develops setup equipment to the experiment and equipment to conduct the
diagrams of equipment to develop equipment connection experiment, equipment connection
connections or wiring. or wiring diagrams. or wiring diagrams.
2. Teamwork [b] Actively engages and Cooperates with other group Distracts or discourages other
cooperates with other group members in a reasonable manner. group members from conducting
members in an the experiment.
effective manner.
3. Conducting Does proper calibration of Calibrates equipment, examines Unable to calibrate appropriate
Experiment [a, c] equipment, carefully examines equipment moving parts, and operatesequipment, and equipment operation
equipment moving parts, and the equipment with minor error. is substantially wrong.
ensures smooth operation and
process.
4. Laboratory Respectfully and carefully observes Observes safety rules and procedures Disregards safety rules and
Safety Rules [a] safety rules and procedures with minor deviation. procedures.
5. Data Collection Plans data collection to achieve Plans data collection to achieve Does not know how to plan data
[a] experimental objectives, and experimental objectives, and collects collection to achieve experimental
conducts an orderly and a complete complete data with minor error. goals; data collected is incomplete and
data collection. contain errors.
6. Data Analysis [a] Accurately conducts simple Conducts simple computations and Unable to conduct simple statistical
computations and statistical analysis statistical analysis using collected data analysis on collected data; no attempt
using collected data; correlates with minor error; reasonably correlates to correlate experimental results with
experimental results to known experimental results to known known theoretical values; incapable of
theoretical values; accounts for theoretical values; attempts to account explaining measurement errors or
measurement errors and parameters for measurement errors and parameters parameters that affect the
that affect experimental results. that affect experimental results. experimental results.
7. Design of Able to design and implement the Able to design and partially implement Unable to design the complete
Experiment [d] complete solution of open-ended the complete solution of open-ended solution of open-ended problem with
problem with safety, health and problem with safety, health and safety, health and environment related
environment related considerations. environment related considerations. considerations.
Total
Lecturer / Faculty
Signature:
Date:
Q2
def linear_search (list, find, start, length):
if start<length:
if list[start] == find:
print("{",find,"} found at position {",start+1,"}")
else:
linear_search(list, find, start+1, length)
else:
print("{",find,"} not found")
list = list()
list=['siraj','ahmed shahzad','jamil','afnan','malik','abdullah','khan','adil shohaz']
find = input("Enter the character you wants to search : ")
length = len(list)
start = 0
linear_search (list, find, start, length)