Searching
Searching — Study Notes
NCERT-aligned · 7 notes · 3 shown free
6.1 INTRODUCTION
Explanation6.1 INTRODUCTION
In our daily lives, we often store various items at home and retrieve them when needed. Sometimes, we remember the exact location of an item, making retrieval straightforward. However, other times we do not remember the exact location and need to search for the required item. Similarly, computers store vast amounts of data that need to be retrieved efficiently when demanded by a user or a program. Searching, in computer science, refers to the process of locating a particular element, called the key, within a collection of elements. The result of a search operation determines whether the key is present in the collection and, if present, its position within the collection. Searching is a fundamental technique in computer science, essential for designing efficient algorithms and data retrieval methods. Programmers must understand various searching techniques to optimize data access and manipulation.
- Searching means locating a particular element (key) in a collection.
- Search results indicate presence or absence of the key and its position if found.
- Computers store large data collections requiring efficient search techniques.
- Understanding searching is essential for designing effective algorithms.
- Searching can be straightforward if the location is known, else requires systematic methods.
- The chapter introduces three primary searching techniques: Linear Search, Binary Search, and Search by Hashing.
- 📌 Searching: Process of locating a particular element in a collection.
- 📌 Key: The element to be searched within a collection.
6.2 LINEAR SEARCH
Explanation6.2 LINEAR SEARCH
Linear Search, also known as sequential or serial search, is the simplest and most fundamental searching technique. It involves checking each element of a list sequentially, starting from the first element and moving towards the last, comparing each element with the key until a match is found or the entire list is traversed. If the key is found, the search is successful, and the position of the key is returned. If the key is not found after checking all elements, the search is unsuccessful. Linear search is exhaustive and does not require the list to be sorted, making it suitable for small or unordered collections. However, it can be inefficient for large lists as it may require checking every element. The algorithm initializes an index at 0 and compares the element at this index with the key. If they match, the search ends. Otherwise, the index is incremented, and the process repeats until the key is found or the list ends. The worst-case scenario occurs when the key is the last element or not present at all, requiring n comparisons for a list of n elements. The best case is when the key is the first element, requiring only one comparison. **Table on page 2 (2×8)** | Index in numList | 0 | 1 | 2 | 3 | 4 | 5 | 6 | | --- | --- | --- | --- | --- | --- | --- | --- | | Value | 8 | -4 | 7 | 17 | 0 | 2 | 19 | **Table on page 3 (5×4)** | index | index < n | numList[index] = key | index=index+1 | | --- | --- | --- | --- | | 0 | 0 < 7 ? Yes | 8 = 17? No | 1 | | 1 | 1 < 7 ? Yes | -4 = 17? No | 2 | | 2 | 2 < 7 ? Yes | 7 = 17? No | 3 | | 3 | 3 < 7 ? Yes | 17 = 17? Yes | | **Table on page 3 (2×8)** | Index in numList | 0 | 1 | 2 | 3 | 4 | 5 | 6 | | --- | --- | --- | --- | --- | --- | --- | --- | | Value | 17 | 8 | -4 | 7 | 0 | 2 | 19 | **Table on page 3 (2×4)** | index | index < n | numList[index] = key | index=index+1 | | --- | --- | --- | --- | | 0 | 0 < 7 ? Yes | 17 = 17? Yes | 1 | **Table on page 16 (12×3)** | 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 |
- Linear search compares each element sequentially with the key.
- It works on unordered lists and is simple to implement.
- Best case: key is first element (1 comparison).
- Worst case: key is last element or absent (n comparisons).
- Useful for small datasets due to its simplicity.
- Algorithm stops immediately when key is found.
- 📌 Linear Search: A search technique that checks each element one by one.
- 📌 Key: The element to be searched in the list.
6.3 BINARY SEARCH
Explanation6.3 BINARY SEARCH
Binary Search is an efficient searching technique that operates on sorted lists. Unlike linear search, which checks elements one by one, binary search exploits the order of elements to reduce the search space by half in each iteration. The process be
Practice Questions — Searching
Includes NCERT exercise questions with answers
Q1.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:
To find the position of each element using linear search, we start from the first element and compare each element with the key until we find a match or reach the end of the list. List: [1, -2, 32, 8, 17, 19, 42, 13, 0, 44] 1) Search for 8: - Pass 1: Compare 1 with 8 → Not equal - Pass 2: Compare -2 with 8 → Not equal - Pass 3: Compare 32 with 8 → Not equal - Pass 4: Compare 8 with 8 → Found at position 4 2) Search for 1: - Pass 1: Compare 1 with 1 → Found at position 1 3) Search for 99: - Pass 1 to 10: Compare each element with 99 → Not found - Result: Element not present 4) Search for 44: - Pass 1 to 9: Compare each element with 44 → Not equal - Pass 10: Compare 44 with 44 → Found at position 10 Detailed table for searching 8 (example): | Pass | Index | Element | Comparison with Key (8) | Decision | |------|-------|---------|------------------------|--------------------| | 1 | 1 | 1 | 1 == 8? No | Continue searching | | 2 | 2 | -2 | -2 == 8? No | Continue searching | | 3 | 3 | 32 | 32 == 8? No | Continue searching | | 4 | 4 | 8 | 8 == 8? Yes | Element found | Similarly, tables can be drawn for other keys. Positions found: - 8 at position 4 - 1 at position 1 - 99 not found - 44 at position 10
Explanation:
Linear search checks each element sequentially until the key is found or the list ends. The position is the index where the key matches the element. For 8, it is found at 4th index after 4 comparisons. For 1, found immediately at 1st index. For 99, not found after checking all elements. For 44, found at last position (10th index).
Q2.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:
Using linear search on the list [42, -2, 32, 8, 17, 19, 42, 13, 8, 44] to find key 8: - Pass 1: 42 != 8 - Pass 2: -2 != 8 - Pass 3: 32 != 8 - Pass 4: 8 == 8 → Found at position 4 The position returned is 4. This means that linear search returns the first occurrence of the key in the list, even if duplicates exist later in the list.
Explanation:
Linear search scans elements from the start and returns the index of the first match found. It does not continue searching for other occurrences once the key is found.
Q3.Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value. Apply linear 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 result.
Answer:
Sample Python program: ```python # Input list of 10 numbers numbers = list(map(int, input('Enter 10 numbers separated by space: ').split())) key = int(input('Enter the key to search: ')) def linear_search(lst, key): for i in range(len(lst)): if lst[i] == key: return i + 1 # Position (1-based) return -1 pos = linear_search(numbers, key) if pos != -1: print(f'Key {key} found at position {pos}') else: print(f'Key {key} not found in the list') # Run for 3 different keys for _ in range(3): key = int(input('Enter key to search: ')) pos = linear_search(numbers, key) if pos != -1: print(f'Key {key} found at position {pos}') else: print(f'Key {key} not found in the list') ``` Explanation: - The program takes a list of 10 integers (both positive and negative). - It defines a linear search function that returns the position of the key if found, else -1. - It searches for the key and prints the result. - The program runs for 3 different keys as requested.
Explanation:
Linear search iterates through the list comparing each element with the key. If found, it returns the position; otherwise, it indicates the key is not present.
Q4.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 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 key values and note the results.
Answer:
Sample Python program: ```python # Input list of 10 integers numbers = list(map(int, input('Enter 10 integers separated by space: ').split())) # Sort the list for binary search numbers.sort() # Binary search function def binary_search(lst, key): low = 0 high = len(lst) - 1 while low <= high: mid = (low + high) // 2 if lst[mid] == key: return mid + 1 # Position (1-based) elif lst[mid] < key: low = mid + 1 else: high = mid - 1 return -1 # Run for 3 different keys for _ in range(3): key = int(input('Enter key to search: ')) pos = binary_search(numbers, key) if pos != -1: print(f'Key {key} found at position {pos}') else: print(f'Key {key} not found in the list') ``` Explanation: - The program sorts the input list to apply binary search. - The binary search function divides the search space by half each iteration. - It returns the position if key is found, else -1. - The program runs for 3 different keys as requested.
Explanation:
Binary search requires a sorted list. It compares the key with the middle element and reduces the search space accordingly until the key is found or search space is empty.
Q5.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] - 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. - Use a Python function to sort/arrange the list in ascending order. - 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. - 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:
Given 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] 1) Linear search on unsorted list: - Search 1: Not found after 24 comparisons - Search 5: Found at position 13 after 13 comparisons - Search 55: Found at position 23 after 23 comparisons - Search 99: Found at position 21 after 21 comparisons 2) Sort the list in ascending order: 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] 3) Linear search on sorted list: - Search 1: Not found after 24 comparisons - Search 5: Found at position 1 after 1 comparison - Search 55: Found at position 12 after 12 comparisons - Search 99: Found at position 24 after 24 comparisons 4) Binary search on sorted list: - Search 1: Iterations: 5 (mid elements checked: 50, 21, 9, 17, 9) Result: Not found - Search 5: Iterations: 4 (mid elements checked: 50, 21, 9, 5) Position: 1 - Search 55: Iterations: 4 (mid elements checked: 50, 68, 55, 50) Position: 12 - Search 99: Iterations: 5 (mid elements checked: 50, 72, 88, 97, 99) Position: 24 Summary: - Linear search comparisons vary depending on position or absence. - Binary search iterations are logarithmic (log2 n). Python code snippets can be used for sorting and searching to verify results.
Explanation:
Linear search checks elements sequentially, so the number of comparisons depends on the position of the key. Binary search divides the search space by half each iteration, so the number of iterations is approximately log2(n). Sorting is required for binary search.
Q6.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]. - 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. - Use a Python function to sort the list. - 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. - 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.
Answer:
Given list: ["Perfect", "Stupendous", "Wondrous", "Gorgeous", "Awesome", "Mirthful", "Fabulous", "Splendid", "Incredible", "Outstanding", "Propitious", "Remarkable", "Stellar", "Unbelievable", "Super", "Amazing"] 1) Linear search on unsorted list: - Amazing: Found at position 16 after 16 comparisons - Perfect: Found at position 1 after 1 comparison - Great: Not found after 16 comparisons - Wondrous: Found at position 3 after 3 comparisons 2) Sort the list: Sorted list = ["Amazing", "Awesome", "Fabulous", "Gorgeous", "Incredible", "Mirthful", "Outstanding", "Perfect", "Propitious", "Remarkable", "Splendid", "Stellar", "Stupendous", "Super", "Unbelievable", "Wondrous"] 3) Linear search on sorted list: - Amazing: Found at position 1 after 1 comparison - Perfect: Found at position 8 after 8 comparisons - Great: Not found after 16 comparisons - Wondrous: Found at position 16 after 16 comparisons 4) Binary search on sorted list: - Amazing: Iterations: 4 (mid words checked: "Outstanding", "Fabulous", "Awesome", "Amazing") Position: 1 - Perfect: Iterations: 4 (mid words checked: "Outstanding", "Splendid", "Perfect", "Propitious") Position: 8 - Great: Iterations: 4 (mid words checked: "Outstanding", "Fabulous", "Awesome", "Incredible") Result: Not found - Wondrous: Iterations: 4 (mid words checked: "Outstanding", "Stellar", "Unbelievable", "Wondrous") Position: 16 Python code can be written to automate these searches and count comparisons/iterations.
Explanation:
Linear search scans sequentially and counts comparisons until the word is found or list ends. Binary search works on sorted list and reduces search space by half each iteration. Words not present result in maximum comparisons or iterations.
Q7.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:
Given: Number of records, n = 2^30 = 1,073,741,824 1) Linear search: - If the person is at the middle position, number of comparisons = n/2 = 2^29 = 536,870,912 2) Binary search: - Number of comparisons = log2(n) + 1 (worst case) - log2(2^30) = 30 - So, approximately 30 comparisons Interpretation: - Linear search requires about 536 million comparisons on average to find the person. - Binary search requires only about 30 comparisons. - Binary search is significantly more efficient for large sorted datasets. Hence, binary search is preferred for searching in large sorted databases.
Explanation:
Linear search checks elements one by one, so average comparisons are half the size of the list. Binary search divides the search space by half each time, so comparisons grow logarithmically with the number of records.
Q8.Use the hash function: h(element)= element%11 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:
Hash function: h(element) = element % 11 Given elements: [44, 121, 55, 33, 110, 77, 22, 66] Calculate hash indices: - 44 % 11 = 0 - 121 % 11 = 0 - 55 % 11 = 0 - 33 % 11 = 0 - 110 % 11 = 0 - 77 % 11 = 0 - 22 % 11 = 0 - 66 % 11 = 0 All elements hash to index 0, so collision occurs. Assuming chaining or linear probing is used: Hash Table (using chaining): Index 0: [44, 121, 55, 33, 110, 77, 22, 66] Index 1 to 10: Empty Search: - 11 % 11 = 0 → Check index 0 list → 11 not found - 44 % 11 = 0 → Check index 0 list → 44 found - 88 % 11 = 0 → Check index 0 list → 88 not found - 121 % 11 = 0 → Check index 0 list → 121 found Search results: - 11: Not found - 44: Found - 88: Not found - 121: Found
Explanation:
All elements hash to the same index 0 causing collisions. Using chaining, all elements are stored in a list at index 0. Search involves checking the list at the computed index. Elements 44 and 121 are found; 11 and 88 are not present.
All 13 Chapters in Computer Science
Computer Science · Class 12