0% found this document useful (0 votes)
39 views

DSA Lab 6

The document describes different searching techniques using Python, including linear search, binary search, and Fibonacci search. It provides pseudocode implementations and explanations of each algorithm. Linear search has O(n) time complexity and is used for unsorted lists. Binary search has O(log n) time complexity and requires a sorted list. It works by repeatedly dividing the search interval in half. Fibonacci search improves upon binary search for large lists by eliminating approximately two-thirds of the remaining list at each step.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

DSA Lab 6

The document describes different searching techniques using Python, including linear search, binary search, and Fibonacci search. It provides pseudocode implementations and explanations of each algorithm. Linear search has O(n) time complexity and is used for unsorted lists. Binary search has O(log n) time complexity and requires a sorted list. It works by repeatedly dividing the search interval in half. Fibonacci search improves upon binary search for large lists by eliminating approximately two-thirds of the remaining list at each step.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

LAB 06

SEARCHING TECHNIQUES
USING PYTHON

STUDENT NAME ROLL NO SEC

SIGNATURE & DATE

MARKS AWARDED:

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING


SCIENCE (NUCES) KARACHI

Prepared by: Engr. Syed Asim Mahmood Summer 2022


[SEARCHING TECHNIQUES USING PYTHON] LAB: 06

Lab Session 06: SEARCHING TECHNIQUES USING PYTHON

OBJECTIVES:
Implementing linear search technique, Binary search technique.

Linear Search Algorithm

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

• It is used for unsorted and unordered small list of elements.

• 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.

• It has a very simple implementation.

Implementing Linear Search


Following are the steps of implementation that we will be following:

1. Traverse the array using a “for loop”.


2. In every iteration, compare the target value with the current value of the array.
3. If the values match, return the current index of the array.
4. If the values do not match, move on to the next array element.
5. If no match is found, return -1.
6. To search the number 5 in the array given below, linear search will go step by step in a
sequential order starting from the first element in the given array.

National University of Computer & Emerging Sciences, Karachi Page | 1


LAB: 06 [SEARCHING TECHNIQUES USING PYTHON]

#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:

Print ("Enter your list:")


mylist = [int(b) for b in input().split()]
find = eval (input ("Enter the search element:"))
length = len (mylist)
start = 0
linear_search (mylist,find,start,length)

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").

Page | 2 National University of Computer & Emerging Sciences, Karachi


[SEARCHING TECHNIQUES USING PYTHON] LAB: 06

1. Binary Search Algorithm:

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.

2. 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.

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)

National University of Computer & Emerging Sciences, Karachi Page | 3


LAB: 06 [SEARCHING TECHNIQUES USING PYTHON]

Features of Binary Search


1. It is great to search through large sorted arrays.

2. It has a time complexity of O(log n) which is a very good time complexity.

3. It has a simple implementation.

Example: Given a sorted list of a [ ] of n elements, search a given element x in list.

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:

First low = 0, high = 8, mid = (low + high) = 4

a[mid] = 65 is the center element, but 65 > 31.

2. So now high = mid - 1= 4 - 1 = 3, low = 0, mid = (0 + 3) / 2 = 1

a[mid] = a[1] = 23, but 23 < 31.

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.

3. Fibonacci Search Algorithm

Fibonacci Numbers are recursively defined as F(n) = F(n-1) + F(n-2), F(0) = 0,


F(1) = 1. First few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

Page | 4 National University of Computer & Emerging Sciences, Karachi


[SEARCHING TECHNIQUES USING PYTHON] LAB: 06

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.

Below is the complete algorithm

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].

3. While the array has elements to be inspected:

a. Compare x with the last element of the range covered by fibMm2

b. If x matches, return index

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?
……………………………………………………………………………………….

National University of Computer & Emerging Sciences, Karachi Page | 5


LAB: 06 [SEARCHING TECHNIQUES USING PYTHON]

Lab Report:
(It is recommended to write Lab Report in bullet Form)

Page | 6 National University of Computer & Emerging Sciences, Karachi


[SEARCHING TECHNIQUES USING PYTHON] LAB: 06

Student Name(s): Roll:


Section:

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:

National University of Computer & Emerging Sciences, Karachi Page | 7


Q1
def bin_search (v_list, v_id, start, end):
if start <= end:
mid = (start+end)/2
mid = int(mid)
if v_list[mid] == v_id:
print("{",v_id,"} found at position {",mid+1,"}")
elif v_list[mid] > v_id:
bin_search (v_list, v_id, start, mid-1)
elif v_list[mid] < v_id :
bin_search (v_list, v_id, mid+1, end)
else:
print ("Voter ID {",v_id,"} not found")
v_list = list()
v_list=[12,24,78,99,105,220,620,738]
v_id = int(input("Please enter the ID you want to search from the given list : "))
end = len(v_list)
start = 0
list.sort(v_list)
print("The sorted list is : ",v_list)
bin_search (v_list, v_id, start, end)

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)

You might also like