Ch-6 Searching
Ch-6 Searching
Chapter – 6
SEARCHING
Introduction
• Searching is the process of locating a specific element (called the key) in a collection.
• It determines whether the key is present and, if so, note down its position.
1. Linear Search
2. Binary Search
3. Search by Hashing
• It compares each element of the list with the key until a match is found or the list ends.
Step 1: SET i= 0
STOP
ELSE
i=i+1
Example List:
List = [8,-4, 7, 17, 0, 2, 19],Key: 17
n=len(list)
for i in range(n):
if list[i] == key:
return i + 1
return None
list = []
for i in range(n):
ele= int(input())
[Link](ele)
key = int(input("Enter the number to be searched:"))
if pos is None:
else:
Binary Search
• This method requires a sorted list.
• Repeatedly divides list into halves and in each pass, compares key with the middle element.
last = mid- 1
Example
2. 0. 6 3. 7. 2 <7→left half
3 0. 2 1. 3. 2 <3→left half
4 0 0 0 2 Match found
last = len(list)- 1
if list[mid] == key:
return mid+1
last = mid - 1
else:
first = mid+ 1
return None
list = []
for i in range(n):
ele=int(input())
[Link](ele)
key = int(input("Enter the number to be searched: "))
if pos is None:
else:
print(key, "is found at position", pos)
• Database indexing.
• Data compression.
Search by Hashing
• Direct access method using a hash function.
• Hashing is a technique which can be used to know the presence of a key in a list in one step.
• Hash function takes elements of a list one by one and generates an Index value for every element.
• Each index of the hash table can hold only one item and the positions are indexed by integer values starting
from 0.
• The size of the hash table can be larger than the size of the list.
• A hash function takes an element from a list and divides it by the size of the hash table and the remainder
generated is called the hash value.
Example
List: [34, 16, 2, 93, 80, 77, 51]
Index. Value
0 None
1 None
2 None
3 None
4 None
5 None
6 None
7 None
8 None
9 None
16 6 6
2 2 2
93 3 3
80 0 0
77 7 7
51 1 1
Index Value
0 80
1 51
2 2
3 93
4 34
5 None
6. 16
7 77
8 None
9. None
def hashFind(hashTable,key):
if hashTable[key % 10] == key:
return None
hashTable = [None]*10
for i in L:
hashTable[i % 10] = i
print("Hash Table contents are: ",hashTable)
pos= hashFind(hashTable,key)
if pos is None:
else:
Collision
• Occurs when multiple elements hash to the same index.
• Requires collision resolution techniques (not covered here).
if key in hashtable:
return hashtable[key]
return None
l=[10,45,3,76,23,87,47,12,32,99]
print(list(enumerate(l)))
hashtable={}
hashtable[num]=i
pos=hashfind(hashtable,key)
if pos is None:
print(key," is not found")
else:
Summary
Technique Best For. List Requirement Time Complexity Notes
Linear Search. Small/Unordered lists. None. O(n) Simple but slow for large n
Binary Search. Large/Sorted lists Sorted. O(log n) Fast, requires sorted input
A) n/2. B) n. C) log2n D) 1
5. Which loop is used in the linear search algorithm provided in the chapter?
A) When the key is the middle element. B) When the list is sorted
C) When the key is the last element. D) When the key is the first element
7. In linear search, if the key is not present in the list, the number of comparisons will be:
A) 0. B) 1. C) n. D) n-1
A) 0. B) 1. C) log2n D) n
12. What happens when the middle element in binary search equals the key?
13. What is the time complexity of binary search in the worst case?
15. What is a requirement for the binary search algorithm to work properly?
17. What is the formula for the remainder method used in hashing?
18. What is the term used when two elements in hashing map to the same index?
C) A function that generates only even indices. D) A function that maps all elements
to unique indices
20. Which search technique is fastest in theory when there are no collisions?
Reason (R): Linear search checks every element sequentially from the beginning of the list.
Options:
22. Assertion (A): Linear search performs the minimum work when the key is at the end of the list.
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 0
II PUC COMPUTER SCIENCE SCANNER
Reason (R): Linear search stops after finding the first occurrence of the key. Options:
A) Both A and R are true, and R is the correct explanation of A.
23. Assertion (A): Binary search is faster than linear search on large datasets.
Reason (R): Binary search reduces the list size by half in every iteration. Options:
Reason (R): Binary search compares the key only with the first and last elements. Options:
Reason (R): Binary search stops only when first > last.
26. Assertion (A): Hashing provides constant time search irrespective of the list size.
Reason (R): Hashing directly accesses the element by calculating its position using a hash
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 1
II PUC COMPUTER SCIENCE SCANNER
function.
27. Assertion (A): A perfect hash function guarantees that no two elements map to the same index.
28. Assertion (A): Binary search modifies the list by deleting elements that are not required.
29. Assertion (A): Collisions in hashing occur when two keys are stored at the same index.
30. Assertion (A): Binary search is efficient only if the list is sorted.
Reason (R): Sorting allows binary search to determine which half to discard.
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 2
II PUC COMPUTER SCIENCE SCANNER
Answer: Searching
2. In linear search, each element is compared with the key in a _______ manner.
Answer: sequential
3. Another name for linear search is _______ search.
Answer: serial
4. The maximum number of comparisons in linear search is equal to _______, where n is the
number of elements.
Answer: n
5. In binary search, the list must be _______ before applying the search.
Answer: sorted
6. Binary search divides the list into _______ parts after every unsuccessful comparison.
Answer: half
9. In hashing, the formula used to compute index using the remainder method is _______.
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3
II PUC COMPUTER SCIENCE SCANNER
Answer: collision
12. The process of finding a new position for elements during collision is known as _______.
Answer: perfect
14. The time complexity of binary search in the worst case is _______.
Answer: O(log n)
15. In the worst case of linear search, the key may be found at the _______ of the list or not present
at all.
Answer: end
2 MAKRS QUESTIONS
1. What is linear search? When is it preferred?
Answer: Linear search is an exhaustive technique where each element in the list is compared sequentially with
the key until the element is found or the list ends. It is preferred for small, unsorted lists.
Answer: Binary search is an efficient search method that repeatedly divides a sorted list into halves and
compares the key with the middle element to find its position. It requires the list to be sorted in ascending or
descending order.
Answer:
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 4
II PUC COMPUTER SCIENCE SCANNER
4. Give the syntax of a simple hash function and one example using element = 34, table size = 10.
Answer: Syntax: hash_value = element % table_size
Answer: A hash table is a list-like structure where elements are stored at specific positions determined by a hash
function. In Python, it can be implemented using a list with predefined size, e.g.: hashTable = [None] * 10
Answer: Collision occurs when two or more elements produce the same hash value and thus map to the same
index. A perfect hash function maps every input to a unique index, ensuring no collisions.
7. How does binary search minimize the number of comparisons during a search?
Answer: Binary search reduces the list size by half after each comparison. By checking whether the key is less
than or greater than the middle element, it eliminates one half of the list in each iteration.
key = 23
Answer:
Answer:
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 5
II PUC COMPUTER SCIENCE SCANNER
3 MARKS QUESTIONS
1. Explain the working of linear search with an example.
Answer: Linear search compares each element in the list with the key from beginning to end.
For example, in the list numList = [8,-4, 7, 17, 0, 2, 19], to find key 17, the comparisons will be:
0. 8. 8 ≠17
1 -4. -4 ≠ 17
2 7. 7 ≠17
3 17 17 = 17
2. Write the algorithm for Binary Search and explain its steps.
Answer: Algorithm: BinarySearch(numList, key)
IF numList[mid] == key
STOP
Explanation: The list is divided repeatedly. Based on comparison with the middle value, only one half is
searched in each iteration.
3. What is a hash function? How is it used to create a hash table? Give an example.
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 6
II PUC COMPUTER SCIENCE SCANNER
hash value = 93 % 10 = 3
This means the element will be placed at index 3 of the hash table.
Answer: Collision occurs when two different elements are assigned the same hash index.
5.. What is collision in hashing? Why does it occur? Explain with an example.
Answer: Collision occurs when two different elements are assigned the same hash index.
Answer:
2. Time complexity is O(log n): More efficient than linear search’s O(n).
3. Fewer comparisons: Especially when the key is near the canter of a sorted list.
5 MARKS QUESTIONS
1. Write an algorithm to search an element Using Linear Search method.
LinearSearch(numList, key, n)
STOP
ELSE
index = index + 1
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 7
II PUC COMPUTER SCIENCE SCANNER
BinarySearch(numList, key)
STOP
last = mid- 1
3. 4. Explain hashing and demonstrate the creation of a hash table using the remainder method with an example.
Answer: Hashing is a technique where a hash function is used to calculate an index for each element.
16. 6. 6
2. 2. 2
93. 3. 3
80. 0 0
77. 7 7
51 1. 1
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 8
II PUC COMPUTER SCIENCE SCANNER
Hash Table: [80, 51, 2, 93, 34, None, 16, 77, None, None]
4. What is collision in hashing? How does it occur? Why is a perfect hash function ideal? Give one
example. Answer:
Collision occurs when two or more elements produce the same hash value and map to the same
index. Example: 16 % 10 = 6 and 26 %10=6→collision at index 6.
This causes a conflict since only one element can occupy a position.
A perfect hash function ensures unique hash values for every input, eliminating collisions.
5. What is the purpose of a hash function? Write a Python program to insert elements into a hash
table and search using hashing.
Answer:
A hash function calculates the index for an element in a hash table using a mathematical operation.
return None
hashTable = [None] * 10
for i in L:
hashTable[i % 10] =i
key = 16
1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 9
II PUC COMPUTER SCIENCE SCANNER
Exercise Solution
Question 1
Answer
1. Item = 8
index 0 1 2 3 4 5 6 7 8 9
elements 1 -2 32 8 17 19 42 13 0 44
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 0
II PUC COMPUTER SCIENCE SCANNER
0 0 < 10 ? Yes 1 = 8 ? No 1
1 1 < 10 ? Yes -2 = 8 ? No 2
2 2 < 10 ? Yes 32 = 8 ? No 3
2. Item = 1
index 0 1 2 3 4 5 6 7 8 9
elements 1 -2 32 8 17 19 42 13 0 44
3. Item = 99
index 0 1 2 3 4 5 6 7 8 9
elements 1 -2 32 8 17 19 42 13 0 44
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 1
II PUC COMPUTER SCIENCE SCANNER
0 0 < 10 ? Yes 1 = 99 ? No 1
1 1 < 10 ? Yes -2 = 99 ? No 2
2 2 < 10 ? Yes 32 = 99 ? No 3
3 3 < 10 ? Yes 8 = 99 ? No 4
4 4 < 10 ? Yes 17 = 99 ? No 5
5 5 < 10 ? Yes 19 = 99 ? No 6
6 6 < 10 ? Yes 42 = 99 ? No 7
7 7 < 10 ? Yes 13 = 99 ? No 8
8 8 < 10 ? Yes 0 = 99 ? No 9
9 9 < 10 ? Yes 44 = ? No 10
10 10 < 10 ? No
Since the item 99 is not found in the list, the linear search algorithm returns -1.
4. Item = 44
index 0 1 2 3 4 5 6 7 8 9
elements 1 -2 32 8 17 19 42 13 0 44
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 2
II PUC COMPUTER SCIENCE SCANNER
0 0 < 10 ? Yes 1 = 44 ? No 1
1 1 < 10 ? Yes -2 = 44 ? No 2
2 2 < 10 ? Yes 32 = 44 ? No 3
3 3 < 10 ? Yes 8 = 44 ? No 4
4 4 < 10 ? Yes 17 = 44 ? No 5
5 5 < 10 ? Yes 19 = 44 ? No 6
6 6 < 10 ? Yes 42 = 44 ? No 7
7 7 < 10 ? Yes 13 = 44 ? No 8
8 8 < 10 ? Yes 0 = 44 ? No 9
Question 2
Use the linear search program to search the key with value 8 in the list having duplicate values such as [42, -2, 32, 8, 17, 19,
42, 13, 8, 44]. What is the position returned? What does this mean?
Answer
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3
II PUC COMPUTER SCIENCE SCANNER
return position
if result != -1:
print("The position of key", key, "in the list is", result)
else:
print("Key", key, "not found in the list.")
Output
Question 3
Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value. Apply l inear
search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the
list otherwise it should print an appropriate message. Run the program for at least 3 different keys and note the res ult.
Answer
Output
Enter the list: [32, -5, 34, 45, -6, 78, 87, 12, -9, 10]
Enter item to be searched for: -5
-5 found at index 1
Enter item to be searched for: 10
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 4
II PUC COMPUTER SCIENCE SCANNER
10 found at index 9
Enter item to be searched for: 100
100 not found
Question 4
Write a program that takes as input a list of 10 integers and a key value and applies binary search to find whether the key i s
present in the list or not. If the key is present it should display the position of the key in the list otherwise it should p rint an
appropriate message. Run the program for at least 3 different key values and note the results.
Answer
if list1[mid] == key:
return mid
elif key < list1[mid]:
last = mid - 1
else:
first = mid + 1
return -1
for i in range(3):
key = int(input("Enter the key to be searched: "))
pos = binarysearch(list1, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
Output
Enter the list: [1, 33, 55, -77, 45, 23, -56, 23, 46, -89]
Enter the key to be searched: 33
33 found at index 1
Enter the key to be searched: 45
45 found at index 4
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 5
II PUC COMPUTER SCIENCE SCANNER
Question 5
[50, 31, 21, 28, 72, 41, 73, 93, 68, 43,
45, 78, 5, 17, 97, 71, 69, 61, 88, 75,
99, 44, 55, 9]
1. Use linear search to determine the position of 1, 5, 55 and 99 in the list. Also note the number of key comparisons
required to find each of these numbers in the list.
2. Use a Python function to sort/arrange the list in ascending order.
3. Again, use linear search to determine the position of 1, 5, 55 and 99 in the list and note the number of key
comparisons required to find these numbers in the list.
4. Use binary search to determine the position of 1, 5, 55 and 99 in the sorted list. Record the number of iterations
required in each case.
Answer
1.
if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 6
II PUC COMPUTER SCIENCE SCANNER
first = mid + 1
original_list = [50, 31, 21, 28, 72, 41, 73, 93, 68, 43, 45, 78, 5, 17, 97, 71,
69, 61, 88, 75, 99, 44, 55, 9]
keys = [1, 5, 55, 99]
original_list.sort()
print("\nSorted List:", original_list)
Output
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 7
II PUC COMPUTER SCIENCE SCANNER
5 found at index 12
Number of comparisons: 13
55 found at index 22
Number of comparisons: 23
99 found at index 20
Number of comparisons: 21
Sorted List: [5, 9, 17, 21, 28, 31, 41, 43, 44, 45, 50, 55, 61, 68, 69, 71, 72,
73, 75, 78, 88, 93, 97, 99]
Question 6
Write a program that takes as input the following unsorted list of English words:
1. Use linear search to find the position of Amazing, Perfect, Great and Wondrous in the list. Also note the number of
key comparisons required to find these words in the list.
2. Use a Python function to sort the list.
3. Again, use linear search to determine the position of Amazing, Perfect, Great and Wondrous in the list and note the
number of key comparisons required to find these words in the list.
4. Use binary search to determine the position of Amazing, Perfect, Great and Wondrous in the sorted list. Record the
number of iterations required in each case.
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 8
II PUC COMPUTER SCIENCE SCANNER
Answer
if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1
2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 9
II PUC COMPUTER SCIENCE SCANNER
original_list.sort()
print("\nSorted List:", original_list)
Output
3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 0
II PUC COMPUTER SCIENCE SCANNER
Number of comparisons: 16
Question 7
Estimate the number of key comparisons required in binary search and linear search if we need to find the details of a person
in a sorted database having 230 (1,073,741,824) records when details of the person being searched lies at the middle position
in the database. What do you interpret from your findings?
Answer
For binary search it will be just 1 comparison, as binary search starts with comparing the element at middle and the search
will be successful with the first comparison as the desired element lies at the middle of the database.
For linear search it will be 115 comparisons, as linear search starts with comparing the first element and keeps on comparing
the successive elements and thus it will take 115 comparisons to reach at the middle element, which is the desired element.
Therefore, for a sorted list, binary search is much more efficient choice for searching compared to linear search.
Question 8
Use the hash function: h(element) = element % 10 to store the collection of numbers: [44, 121, 55, 33, 110, 77, 22, 66] in a
hash table. Display the hash table created. Search if the values 11, 44, 88 and 121 are present in the hash table, and display
the search results.
Answer
hashTable = [None, None, None, None, None, None, None, None, None, None]
3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 1
II PUC COMPUTER SCIENCE SCANNER
for i in range(0,len(L)):
hashTable[L[i]%10] = L[i]
Output
Question 9
Write a Python program by considering a mapping of list of countries and their capital cities such as:
3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 2
II PUC COMPUTER SCIENCE SCANNER
'Australia': 'Canberra'}
Let us presume that our hash function is the length of the Country Name. Take two lists of appropriate size : one for keys
(Country) and one for values (Capital). To put an element in the hash table, compute its hash code by counting the number of
characters in Country, then put the key and value in both the lists at the corresponding indices. For example, India has a hash
code of 5. So, we store India at the 5th position (index 4) in the keys list, and New Delhi at the 5th position (index 4) in the
values list and so on. So that we end up with:
0 None None
1 UK London
2 None None
3 Cuba Havana
5 France Paris
6 None None
7 None None
8 Australia Canberra
9 None None
10 Switzerland Berne
Now search the capital of India, France and the USA in the hash table and display your result.
Answer
3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3
II PUC COMPUTER SCIENCE SCANNER
keys = [None, None, None, None, None, None, None, None, None, None, None]
values = [None, None, None, None, None, None, None, None, None, None, None]
def calculate_hash_index(key):
return len(key) - 1
for i in range(len(keys)):
print(str(i) + "| " + str(keys[i]) + "| " + str(values[i]))
search_keys = ['India', 'France', 'USA']
print("\nSearch Results:")
for key in search_keys:
index = calculate_hash_index(key)
if keys[index] == key:
print("Capital of", key, ":", values[index])
else:
print("Capital of ", key, ": Not found")
Output
Search Results:
Capital of India : New Delhi
Capital of France : Paris
Capital of USA : Not found
3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 4