0% found this document useful (0 votes)
98 views34 pages

Ch-6 Searching

The document discusses three main searching techniques: Linear Search, Binary Search, and Search by Hashing. Linear Search is suitable for small or unsorted lists, while Binary Search is more efficient for sorted lists. Hashing allows for constant time searches and requires a hash function to generate index values for elements.

Uploaded by

sagar200720
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views34 pages

Ch-6 Searching

The document discusses three main searching techniques: Linear Search, Binary Search, and Search by Hashing. Linear Search is suitable for small or unsorted lists, while Binary Search is more efficient for sorted lists. Hashing allows for constant time searches and requires a hash function to generate index values for elements.

Uploaded by

sagar200720
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

II PUC COMPUTER SCIENCE SCANNER

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.

• Three main techniques:

1. Linear Search

2. Binary Search

3. Search by Hashing

Linear Search (Sequential Search)

• It compares each element of the list with the key until a match is found or the list ends.

• Useful for unsorted or small-sized lists.

Algorithm for Linear Search


LinearSearch(List, key, n)

Step 1: SET i= 0

Step 2: WHILE i < n, REPEAT Step 3

Step 3: IF List[i] ==key THEN

PRINT “Element found at position”, i+1

STOP

ELSE
i=i+1

Step 4: PRINT “Search unsuccessful”

Example List:
List = [8,-4, 7, 17, 0, 2, 19],Key: 17

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 1


II PUC COMPUTER SCIENCE SCANNER

Index Comparison. Result


0. 8 ==17 not found
1. -4 == 17. not found
2. 7 ==17. not found
3. 17 == 17. Found at index 3

Linear Search Program


def linearSearch(list, key):

n=len(list)

for i in range(n):

if list[i] == key:
return i + 1

return None

list = []

n = int(input("How many elements in your list? "))

for i in range(n):

ele= int(input())

[Link](ele)
key = int(input("Enter the number to be searched:"))

pos = linearSearch(list, key)

if pos is None:

print("Number", key, "is not present in the list")

else:

print("Number", key, "is present at position", pos)

Binary Search
• This method requires a sorted list.

• It is more efficient than linear search.

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 2


II PUC COMPUTER SCIENCE SCANNER

• Repeatedly divides list into halves and in each pass, compares key with the middle element.

Algorithm of Binary Search


BinarySearch(List, key)

Step 1: SET first = 0, last = n- 1

Step 2: WHILE first <= last, REPEAT Step 3

Step 3: SET mid = (first + last)//2

IF List[mid] == key THEN

PRINT "Element found at position", mid + 1


STOP
ELSE IF List[mid] > key THEN

last = mid- 1

ELSE first = mid + 1

Step 4: PRINT "Search unsuccessful"

Example

List = [2,3,5,7,10,11,12,17,19,23,29,31,37,41,43], Key: 2


Here’s the corrected and neatly formatted table in Markdown:

Step Low High. Mid. MidValue Comparison

1. 0. 14. 7 17. 2 <17→left half

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

Minimum iterations: 1 (if key is in middle)

Maximum iterations: log2(n)

Binary Search Program in Python

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3


II PUC COMPUTER SCIENCE SCANNER

def binarySearch(list, key):


first = 0

last = len(list)- 1

while first <= last:

mid = (first + last)//2

if list[mid] == key:

return mid+1

elif key < list[mid]:

last = mid - 1
else:

first = mid+ 1

return None

list = []

n=int(input("Enter the number of elements to List"))

print("Enter the number of elements in ascending order :")

for i in range(n):
ele=int(input())

[Link](ele)
key = int(input("Enter the number to be searched: "))

pos = binarySearch(list, key)

if pos is None:

print(key, "is not found in the list")

else:
print(key, "is found at position", pos)

Applications of Binary Search


• Dictionary/telephone directory search.

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 4


II PUC COMPUTER SCIENCE SCANNER

• Database indexing.
• Data compression.

• Implementing routing tables in routers, etc.

Search by Hashing
• Direct access method using a hash function.

• Searches key in constant time O(1).

• Hashing is a technique which can be used to know the presence of a key in a list in one step.

• Hashing makes searching operations very efficient.

• Hash function takes elements of a list one by one and generates an Index value for every element.

• This will generate a new list called the Hash Table.

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

• Hash function computes index:

h(element) = element % size(Hash Table).

Example
List: [34, 16, 2, 93, 80, 77, 51]

Consider an Empty hash table with 10 positions.

Index. Value
0 None

1 None

2 None

3 None
4 None
5 None

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 5


II PUC COMPUTER SCIENCE SCANNER

6 None
7 None

8 None

9 None

Hash Table size = 10

Element Hash Value. Index in Table


34. 4 4

16 6 6

2 2 2
93 3 3

80 0 0

77 7 7

51 1 1

Final Hash Table:

Index Value

0 80
1 51

2 2
3 93

4 34

5 None

6. 16

7 77
8 None

9. None

Hashing Program in Python

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 6


II PUC COMPUTER SCIENCE SCANNER

def hashFind(hashTable,key):
if hashTable[key % 10] == key:

return (key % 10) + 1

return None

hashTable = [None]*10

print("Empty Hash Table is ",hashTable)

L = [34, 16, 2, 93, 80, 77, 51]

for i in L:

hashTable[i % 10] = i
print("Hash Table contents are: ",hashTable)

key = int(input("Enter the number to be searched: "))

pos= hashFind(hashTable,key)

if pos is None:

print("Number", key, "is not present in the hash table")

else:

print("Number", key, "present at", pos, "position")

Collision
• Occurs when multiple elements hash to the same index.
• Requires collision resolution techniques (not covered here).

• A perfect hash function prevents collision by mapping each element uniquely.

Python Program using hashing technique to prevent collision.


def hashfind(hashtable,key):

if key in hashtable:

return hashtable[key]
return None

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 7


II PUC COMPUTER SCIENCE SCANNER

l=[10,45,3,76,23,87,47,12,32,99]
print(list(enumerate(l)))

hashtable={}

for i,num in enumerate(l):

hashtable[num]=i

print("Hash Table contents are",hashtable)

key=int(input("Enter the key to be search"))

pos=hashfind(hashtable,key)

if pos is None:
print(key," is not found")

else:

print(key," is found at position ",pos)

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

Hashing. Fastest lookups. Hash Function O(1) Needs collision handling

MULTIPLE CHOICE QUESTION (MCQ)


1. What is the primary goal of searching in computer science?

A) To delete elements from a list B) To sort a list

C) To locate a specific element in a list D) To multiply elements in a list

2. Which of the following is another name for linear search?

A) Quick search. B) Divide and conquer search

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 8


II PUC COMPUTER SCIENCE SCANNER

C) Serial search D) Binary search


3. In linear search, how many comparisons are required in the worst case for a list of n elements?

A) n/2. B) n. C) log2n D) 1

4. Linear search is most suitable when the list is:

A) Sorted. B) Encrypted. C) Small and unsorted. D) Large and ordered

5. Which loop is used in the linear search algorithm provided in the chapter?

A) for loop. B) while loop. C) do-while loop. D) nested loop

6. In which case will linear search make only one comparison?

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

8. What is returned by the linearSearch() function if the key is not found?

A) 0. B) -1. C) None. D) The index of last element

9. Binary search works only on:

A) Encrypted lists B) Hashed lists. C) Sorted lists D) Lists with no duplicates


10. What is the mid index calculated as in the binary search algorithm?

A) (first + last) / 2. B) (first + last) % 2. C) (first + last) // 2. D) (first + last) * 2


11. In the best case, binary search takes how many iterations to find the key?

A) 0. B) 1. C) log2n D) n

12. What happens when the middle element in binary search equals the key?

A) The list is reversed. B) The key is ignored


C) The search continues. D) The key is found and search terminates

13. What is the time complexity of binary search in the worst case?

A) O(n²) B) O(n) C) O(log n) D) O(1)


14. Binary search reduces the list size by:

MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 9


II PUC COMPUTER SCIENCE SCANNER

A) One element each time. B) Two elements each time


C) Half each time. D) None of the above

15. What is a requirement for the binary search algorithm to work properly?

A) The list must be hashed. B) The list must be unsorted

C) The key must be negative. D) The list must be sorted

16. What does hashing use to calculate the position of an element?

A) Key length. B) Sorting function. C) Hash function. D) Index counter

17. What is the formula for the remainder method used in hashing?

A) element // table size. B) element % table size


C) element + table size D) element- table size

18. What is the term used when two elements in hashing map to the same index?

A) Mapping. B) Modulo clash. C) Collision. D) Duplication

19. What is a perfect hash function?

A) A function that sorts a list. B) A function that encrypts elements

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?

A) Linear search. B) Binary search. C) Hash-based search. D) Sequential search


21. Assertion (A): Linear search is suitable for small and unsorted lists.

Reason (R): Linear search checks every element sequentially from the beginning of the list.

Options:

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.
C) A is true, but R is false.

D) A is false, but R is true.

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.

B) Both A and R are true, but R is not the correct explanation of A.

C) A is false, but R is true.


D) Both A and R are false.

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:

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.
C) A is false, but R is true.

D) Both A and R are false.

24. Assertion (A): Binary search works efficiently on unsorted data.

Reason (R): Binary search compares the key only with the first and last elements. Options:

A) Both A and R are true, and R is the correct explanation of A.

B) A is true, but R is false.

C) A is false, but R is true.

D) Both A and R are false.


25. Assertion (A): In binary search, if the key is not found, the list size continues to reduce until one
element remains.

Reason (R): Binary search stops only when first > last.

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.

C) A is true, but R is false.


D) Both A and R are false.

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.

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.

C) A is false, but R is true.

D) Both A and R are false.

27. Assertion (A): A perfect hash function guarantees that no two elements map to the same index.

Reason (R): Perfect hash functions are collision-prone.

A) Both A and R are true, and R is the correct explanation of A.

B) Both A and R are true, but R is not the correct explanation of A.

C) A is true, but R is false.


D) Both A and R are false.

28. Assertion (A): Binary search modifies the list by deleting elements that are not required.

Reason (R): The search area reduces by half in each iteration.

A) Both A and R are true, and R is the correct explanation of A.

B) A is true, but R is false.

C) A is false, but R is true.


D) Both A and R are false.

29. Assertion (A): Collisions in hashing occur when two keys are stored at the same index.

Reason (R): The modulo division method always avoids collisions.

A) Both A and R are true, and R is the correct explanation of A.

B) Both A and R are true, but R is not the correct explanation of A.

C) A is true, but R is false.


D) Both A and R are false.

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

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.

C) A is false, but R is true.

D) Both A and R are false.

FILL IN THE BLANKS


1. The process of locating a particular element in a collection of elements is called _______.

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: two / halves

7. The mid index in binary search is calculated as _______.

Answer: (first + last) // 2


8. Binary search reduces the search area by _______ each time.

Answer: half
9. In hashing, the formula used to compute index using the remainder method is _______.

Answer: element % size of hash table


10. The table where elements are stored using hash function values is called a _______.

1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3
II PUC COMPUTER SCIENCE SCANNER

Answer: hash table


11. A situation where two or more elements map to the same index in a hash table is called a _______.

Answer: collision
12. The process of finding a new position for elements during collision is known as _______.

Answer: collision resolution


13. A hash function that maps every key to a unique index is called a _______ hash function.

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.

2. What is binary search? State its requirement?

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.

3. Differentiate between Linear Search and Binary Search.

Answer:

Linear Search Binary Search


Works on unsorted or sorted lists. Works only on sorted lists

Time complexity is O(n) Time complexity is O(log n)


Compares each element sequentially. Divides list and compares with middle

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

Example: 34 % 10 = 4→So,element34will be stored at index 4 of the hash table.

5. What is a hash table? How is it implemented in Python?

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

6. Define ‘collision’ in hashing. What is a perfect hash function?

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.

8. Write the output of the following:

L = [12, 23, 3,-45]

key = 23

position = linearSearch(L, key)


print(position)

Answer: The key 23 is found at position 2 (index + 1).

So the output is: 2


9. List any two applications of binary search.

Answer:

1. Searching a word in a dictionary or telephone directory

2. Implementing indexing in databases and routing tables in routers


10. Give any two differences between binary search and hashing.

Answer:

Binary Search Hashing


Works only on sorted lists. Works on any list (hash function based)

1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 5
II PUC COMPUTER SCIENCE SCANNER

Requires multiple comparisons (log n) Ideally needs only one comparison.

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:

Index Value. Comparison

0. 8. 8 ≠17

1 -4. -4 ≠ 17

2 7. 7 ≠17

3 17 17 = 17

Search is successful at position 4.

2. Write the algorithm for Binary Search and explain its steps.
Answer: Algorithm: BinarySearch(numList, key)

Step 1: SET first = 0, last = n- 1

Step 2: WHILE first <= last mid = (first + last)//2

IF numList[mid] == key

PRINT "Element found at position", mid+1

STOP

ELSE IF numList[mid] > key


last = mid- 1

ELSE first = mid + 1

Step 3: PRINT "Search unsuccessful"

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.

Answer: A hash function computes an index using a mathematical formula.

1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 6
II PUC COMPUTER SCIENCE SCANNER

Example: h(element) = element % size_of_table


For element = 93 and table size = 10,

hash value = 93 % 10 = 3

This means the element will be placed at index 3 of the hash table.

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

Example: Using h(element) = element % 10, 16 % 10 = 6and26 % 10 = 6→bothmaptoindex6 This causes a


collision since both elements can’t occupy the same slot.

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.

Example: Using h(element) = element


6. List three advantages of binary search over linear search.

Answer:

1. Faster for large lists: It reduces comparisons using a divide-and-conquer method.

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)

Step 1: SET index = 0

Step 2: WHILE index < n, REPEAT Step 3


Step 3: IF numList[index] = key THEN

PRINT “Element found at position”, index+1

STOP

ELSE

index = index + 1

1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 7
II PUC COMPUTER SCIENCE SCANNER

Step 4: PRINT “Search unsuccessful”

2. Write an algorithm to search an element Using Binary Search method.

BinarySearch(numList, key)

Step 1: SET first = 0, last = n- 1

Step 2: WHILE first <= last, REPEAT Step 3

Step 3: SET mid = (first + last)//2

IF numList[mid] == key THEN


PRINT "Element found at position", mid + 1

STOP

ELSE IF numList[mid] > key THEN

last = mid- 1

ELSE first = mid + 1

Step 4: PRINT "Search unsuccessful"

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.

Formula: h(element) = element % size_of_hash_table


Example: List: [34, 16, 2, 93, 80, 77, 51], table size = 10

Element. Hash. Value Index


34. 4. 4

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.

def hashFind(key, hashTable):

if hashTable[key % 10] == key:

return (key % 10) + 1

return None

hashTable = [None] * 10

L = [34, 16, 2, 93, 80, 77, 51]

for i in L:

hashTable[i % 10] =i

key = 16

position = hashFind(key, hashTable)

print("Found at position", position) if position else print("Not found")

1
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 9
II PUC COMPUTER SCIENCE SCANNER

Exercise Solution

Question 1

Using linear search determine the position of 8, 1, 99 and 44 in the list:

[1, -2, 32, 8, 17, 19, 42, 13, 0, 44]


Draw a detailed table showing the values of the variables and the decisions taken in each pass of linear search.

Answer

list1 = [1, -2, 32, 8, 17, 19, 42, 13, 0, 44]


n = 10

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

The step-by-step process of linear search is as follows:

2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 0
II PUC COMPUTER SCIENCE SCANNER

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 8 ? No 1

1 1 < 10 ? Yes -2 = 8 ? No 2

2 2 < 10 ? Yes 32 = 8 ? No 3

3 3 < 10 ? Yes 8 = 8 ? Yes

Therefore, for item 8, linear search returns 3 (index).

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

The step-by-step process of linear search is as follows:

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 1 ? Yes

Therefore, for item 1, linear search returns 0 (index).

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

The step-by-step process of linear search is as follows:

2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 1
II PUC COMPUTER SCIENCE SCANNER

index index < n list1[index] = key index = index + 1

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

The step-by-step process of linear search is as follows:

2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 2
II PUC COMPUTER SCIENCE SCANNER

index index < n list1[index] = key index = index + 1

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

9 9 < 10 ? Yes 44 = 44 ? yes

Therefore, for item 44, linear search returns 9 (index).

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

def linear_search(lst, key):


position = -1
for i in range(len(lst)):
if lst[i] == key:
position = i
break

2
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 3
II PUC COMPUTER SCIENCE SCANNER

return position

lst = [42, -2, 32, 8, 17, 19, 42, 13, 8, 44]


key = 8
result = linear_search(lst, key)

if result != -1:
print("The position of key", key, "in the list is", result)
else:
print("Key", key, "not found in the list.")

Output

The position of key 8 in the list is 3


It will return the index 3 (position 4) for the value 8, because at this index first 8 is encountered. Simple linear search returns
the index of first successful match.

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

def lsearch(list1, key):


for k in range(0, len(list1)):
if key == list1[k]:
return k
return -1
list1 = eval(input("Enter the list: "))
for i in range(3):
item = int(input("Enter item to be searched for: "))
pos = lsearch(list1, item)
if pos == -1:
print(item, "not found")
else:
print(item, "found at index", pos)

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

def binarysearch(list1, key):


first = 0
last = len(list1) - 1

while first <= last:


mid = (first + last) // 2

if list1[mid] == key:
return mid
elif key < list1[mid]:
last = mid - 1
else:
first = mid + 1

return -1

list1 = eval(input("Enter the list: "))

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

Enter the key to be searched: 99


99 not found

Question 5

Following is a list of unsorted/unordered numbers:

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

def linear_search(arr, key):


comparisons = 0
for k in range(len(arr)):
comparisons += 1
if key == arr[k]:
return k, comparisons
return -1, comparisons

def binary_search(arr, key):


comparisons = 0
first = 0
last = len(arr) - 1

while first <= last:


mid = (first + last) // 2
comparisons += 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

return -1, comparisons

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]

print("Linear Search on Unsorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

original_list.sort()
print("\nSorted List:", original_list)

print("\nLinear Search on Sorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

print("\nBinary Search on Sorted List:")


for key in keys:
pos, comparisons = binary_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

Output

Linear Search on Unsorted List:


1 not found

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]

Linear Search on Sorted List:


1 not found
5 found at index 0
Number of comparisons: 1
55 found at index 11
Number of comparisons: 12
99 found at index 23
Number of comparisons: 24

Binary Search on Sorted List:


1 not found
5 found at index 0
Number of comparisons: 4
55 found at index 11
Number of comparisons: 1
99 found at index 23
Number of comparisons: 5

Question 6

Write a program that takes as input the following unsorted list of English words:

[Perfect, Stupendous, Wondrous, Gorgeous, Awesome,


Mirthful, Fabulous, Splendid, Incredible,
Outstanding, Propitious, Remarkable, Stellar,
Unbelievable, Super, Amazing].

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

def linear_search(arr, key):


comparisons = 0
for k in range(len(arr)):
comparisons += 1
if key == arr[k]:
return k, comparisons
return -1, comparisons

def binary_search(arr, key):


comparisons = 0
first = 0
last = len(arr) - 1

while first <= last:


mid = (first + last) // 2
comparisons += 1

if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1

return -1, comparisons

original_list = ['Perfect', 'Stupendous', 'Wondrous',


'Gorgeous', 'Awesome', 'Mirthful', 'Fabulous', 'Splendid',
'Incredible', 'Outstanding', 'Propitious', 'Remarkable',
'Stellar', 'Unbelievable', 'Super', 'Amazing']

keys = ['Amazing', 'Perfect', 'Great', 'Wondrous']

print("Linear Search on Unsorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

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)

print("\nLinear Search on Sorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

print("\nBinary Search on Sorted List:")


for key in keys:
pos, comparisons = binary_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

Output

Linear Search on Unsorted List:


Amazing found at index 15
Number of comparisons: 16
Perfect found at index 0
Number of comparisons: 1
Great not found
Wondrous found at index 2
Number of comparisons: 3

Sorted List: ['Amazing', 'Awesome', 'Fabulous', 'Gorgeous', 'Incredible',


'Mirthful', 'Outstanding', 'Perfect', 'Propitious', 'Remarkable', 'Splendid',
'Stellar', 'Stupendous', 'Super', 'Unbelievable', 'Wondrous']

Linear Search on Sorted List:


Amazing found at index 0
Number of comparisons: 1
Perfect found at index 7
Number of comparisons: 8
Great not found
Wondrous found at index 15

3
MR. PRABHAKAR N.K HOD OF COMPUTER SCIENCE, EXCEL PU COLLEGE,GURUVAYANAKERE 0
II PUC COMPUTER SCIENCE SCANNER

Number of comparisons: 16

Binary Search on Sorted List:


Amazing found at index 0
Number of comparisons: 4
Perfect found at index 7
Number of comparisons: 1
Great not found
Wondrous found at index 15
Number of comparisons: 5

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

def h(element, hashTable):


if (hashTable[element % 10] == key):
return ((element % 10) + 1)
else:
return -1

hashTable = [None, None, None, None, None, None, None, None, None, None]

print("We have created a hashTable of 10 positions:")


print(hashTable)
L = [44, 121, 55, 33, 110, 77, 22, 66]
print("The given list is", L[::] )

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]

print("The hash table contents are: " )


for i in range(0,len(hashTable)):
print("hashindex=", i," , value =", hashTable[i])

keys = [11, 44, 88, 121]


for key in keys:
position = h(key,hashTable)
if position == -1:
print("Number",key,"is not present in the hash table")
else:
print("Number ",key," present at ",position, " position")

Output

We have created a hashTable of 10 positions:


[None, None, None, None, None, None, None, None, None, None]
The given list is [44, 121, 55, 33, 110, 77, 22, 66]
The hash table contents are:
hashindex= 0 , value = 110
hashindex= 1 , value = 121
hashindex= 2 , value = 22
hashindex= 3 , value = 33
hashindex= 4 , value = 44
hashindex= 5 , value = 55
hashindex= 6 , value = 66
hashindex= 7 , value = 77
hashindex= 8 , value = None
hashindex= 9 , value = None
Number 11 is not present in the hash table
Number 44 present at 5 position
Number 88 is not present in the hash table
Number 121 present at 2 position

Question 9

Write a Python program by considering a mapping of list of countries and their capital cities such as:

CountryCapital= {'India':'New Delhi','UK':


'London','France':'Paris',
'Switzerland': 'Berne',

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:

hash index = length of key - 1 List of Keys List of Values

0 None None

1 UK London

2 None None

3 Cuba Havana

4 India New Delhi

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

CountryCapital = {'India': 'New Delhi', 'UK': 'London', 'France': 'Paris',


'Switzerland': 'Berne', 'Australia': 'Canberra'}

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 country, capital in [Link]():


index = calculate_hash_index(country)
keys[index] = country
values[index] = capital

print("hash index = length of key - 1 | List of Keys | List of Values")

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

hash index = length of key - 1 | List of Keys | List of Values


0| None| None
1| UK| London
2| None| None
3| None| None
4| India| New Delhi
5| France| Paris
6| None| None
7| None| None
8| Australia| Canberra
9| None| None
10| Switzerland| Berne

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

You might also like