DS Lecture1 1
DS Lecture1 1
hoice(1/2/3/4): 3
break
if found == False:
print(Item, ' was not found in the list!')
#Output
List has the items: [16, 2, 7, 5, 12, 54, 21, 9, 64, 12]
Enter a number to search for: 7
7 was found in the list at index 2
#Method 2: Linear search using def().
def linear(x,y): for i in x:
if i ==y:
return true return false
x = [12, 37, 45, 89, 1, 2, 34, 48, 9]
linear(x,2)
linear(x,9) linear(x,5)
#Output
True
True
False
Linear Search in Python:
Python is one of the most popular and powerful languages. It takes
a few lines to execute the code, which makes it much user-friendly
language. In this tutorial, we will learn the linear search in Python.
Searching is a technique to find the particular element is present
or not in the given list.
There are two types of searching:
1. Linear Search
2. Binary Search
What is a Linear Search?
Linear search is a method of finding elements within a list. It is also called a
sequential search. It is the simplest searching algorithm because it searches the
desired element in a sequential manner.
It compares each and every element with the value that we are searching for. If
both are matched, the element is found, and the algorithm returns the key's index
Program in Python:
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Program in Python (User inputted number):
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = int(input('Enter a number to search for: '))
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Concept of Binary Search:
In the binary search algorithm, we can find the element position using the following methods.
We have a sorted list of elements, and we are looking for the index position of 45.
[12, 24, 32, 39, 45, 50, 54]
So, we are setting two pointers in our list. One pointer is used to denote the smaller value called low and the second pointer is
used to denote the highest value called high.
Next, we calculate the value of the middle element in the array.
mid = (low+high)/2
Here, the low is 0 and the high is 7.
mid = (0+7)/2
mid = 3 (Integer)
Now, we will compare the searched element to the mid index value. In this case, 32 is not equal to 45. So we need to do further
comparison to find the element.
If the number we are searching equal to the mid. Then return mid otherwise move to the further comparison.
The number to be search is greater than the middle number, we compare the n with the middle element of the elements on the
right side of mid and set low to low = mid + 1.
Repeat until the number that we are searching for is found.
Implement a Binary Search in Python:
First, we implement a binary search with the iterative method. We will repeat a set of statements and
iterate every item of the list. We will find the middle value until the search is complete.
# Iterative Binary Search Function method Python Implementation # It returns index of n in given list1 if present, # e
lse returns -1
2. Here, n is the number of elements in the array, which is 10. So lower = 0 and upper = 9 (10-1 = 9)
3. Calculate the mid index as mid = (lower + upper) / 2. In this case, mid = (0 + 9) / 2 = 4.
4. Compare the value at arr[mid] with the target value 23. Here arr[mid] is arr[4], which is 16.
5. Since 16 is less than 23, the target is greater than the mid element. So set lower = mid +
This eliminates the left half of the array.
6. Recalculate mid index with new lower and upper bounds. mid = (lower + upper) / 2 = (5+ 9) / 2 = 7
7. Check if arr[mid] (which is 38) equals target. It does not. Since 38 > 23, set upper = mid - 1
This eliminates the right half.
8. Recalculate mid as (lower + upper) / 2 = (5 + 6) / 2 = 5
9. Check arr[mid] (which is 23) against the target 23. It matches!
10. Return the index mid.
Concept of Binary Search
In the binary search algorithm, we can find the element position using the following methods:
1. Recursive Method
2. Iterative Method
The divide-and-conquer approach technique is followed by the recursive method. In this method, a function is called again and
again until it finds an element in the list.
We have a sorted list of elements, and we are looking for the index position of 45. [12, 24, 32, 39, 45, 50, 54]
So, we are setting two pointers in our list. One pointer is used to denote the smaller value called low, and the second pointer is
used to denote the highest value called high.
Next, we calculate the value of the middle element in the array.
Now, we will compare the searched element to the mid-index value. In this case, 32 is not equal to 45. So we need to do further
comparisons to find the element.
If the number we are searching for is equal to the mid, then return the mid; otherwise, move to the next comparison.
The number to be searched is greater than the middle number, so we compare the n with the middle element of the elements on
the right side of mid and set low to low = mid + 1.
Otherwise, compare the n with the middle element of the elements on the left side of mid, and set high to high = mid—1.
# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present, # else returns -1
OUT PUT
Element is present at index 4
Explanation:
In the above program - We have created a function called binary_search() function which takes two arguments
— a list to sorted and a number to be searched.
We have declared two variables to store the lowest and highest values in the list.
The low is assigned initial value to 0, high to len (list1) — 1 and mid as 0.
Next, we have declared the while loop with the condition that the lowest is equal and smaller than the highest
The while loop will iterate if the number has not been found yet.
In the while loop, we find the mid value and compare the index value to the number we are searching for.
If the value of the mid-index is smaller than n, we increase the mid value by 1 and assign it to The search moves to
the left side.
Otherwise, decrease the mid value and assign it to the high. The search moves to the right side. If the n is equal to
the mid value then return mid.
This will happen until the low is equal and smaller than the high.
If we reach at the end of the function, then the element is not present in the list. We return -1 to the calling
function.
Recursive Binary Search:
The recursion method can be used in the binary search. In this, we will define recursive function
that keeps calling itself until it meets the condition.
Python Program
Python program for recursive binary search
# Returns index position of n in list1 if present, otherwise -1 def binary_search (list1, low, high, n):
# Check base case for the recursive function if low <= high:
mid = (low + high) // 2
# If element is available at the middle itself then return the its index if list1[mid] == n:
return mid
# If the element is smaller than mid value, then search moves
# left sublist1
elif list1[mid] > n:
return binary_search(list1, low, mid - 1, n)
# Test list1ay
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 32
# Function call
res = binary_search(list1, 0, len(list1)-1, n) if res != -1:
print("Element is present at index", str(res))
else:
print("Element is not present in list1")
Output:
Element is present at index 2
Explanation
The above program is similar to the previous program. We declared a recursive function and its base condition. The
condition is the lowest value is smaller or equal to the highest value.
1. We calculate the middle number as in the last program.
2. We have used the if statement to proceed with the binary search.
3. If the middle value equal to the number that we are looking for, the middle value is returned.
4. If the middle value is less than the value, we are looking then our recursive function
5. binary_search() again and increase the mid value by one and assign to low.
6. If the middle value is greater than the value we are looking then our recursive function
7. binary_search() again and decrease the mid value by one and assign it to low.
In the last part, we wrote our main program. It is the same as the previous program, but the only difference is that
we have passed two parameters in the binary_search() function.
This is because we can’t assign the initial values to the low, high and mid in the recursive function. Every
time the recursive is called the value will be reset for those variables. That will give the wrong result.
Python implementation
import math
low = 0
end = len(lst) -1
while low <= end:
mid = math.floor((low + end)/2)
if key == lst[mid]:
return f 'key {key} = lst[{mid}]'
elif