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

Lab 4

This document provides instructions for implementing searching and sorting techniques in Python as part of a programming for engineers course. Students are asked to write functions to perform linear search, binary search, selection sort, and bubble sort on lists of elements. Linear search sequentially checks each element to find a target, while binary search recursively checks the middle element of a sorted list to narrow the search.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Lab 4

This document provides instructions for implementing searching and sorting techniques in Python as part of a programming for engineers course. Students are asked to write functions to perform linear search, binary search, selection sort, and bubble sort on lists of elements. Linear search sequentially checks each element to find a target, while binary search recursively checks the middle element of a sorted list to narrow the search.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Programming for Engineers (ENG 101)

LAB 4

Searching and Sorting Techniques

Dep. of Electrical and Computer Engineering


School of Engineering and Digital Sciences
Implement the following Searching and Sorting techniques in Python by using functions.

i) Linear Search ii) Binary Search

iii) Selection Sort iv) Bubble Sort

Searching Techniques:

Searching is the process of finding the location of a target element among a list of elements.

Here, we are going to discuss about the following two searching techniques:

1. Sequential search or linear search


2. Binary search

1. Sequential search or linear search Technique:


This is the simplest of all searching techniques.
In this method the list is need not be in sorted order.
The key element which is to be searched is compared with each element of the list one by one. If match
exists, element is found. Otherwise end of list is reached, means search fails, element not found in the
list.

Procedure:

1. Read the search element from the user.


2. Compare the search element with the first element in the list.
3. If both are matched, then display "Given element is found!!!" and terminate the function.
4. If both are not matched, then compare search element with the next element in the list.
5. Repeat steps 3 and 4 until search element is compared with last element in the list.
6. If last element in the list also doesn't match, then display "Element is not found!!!" and terminate the
function.

2
Advantages:

It is a simple technique.
This technique works well for lists with smaller size.
The elements in the list need not be in any sorted order.

Disadvantage:

This method is inefficient when large number of elements are placed in list, because time taken for
search is more.

Python program to implement Linear search technique.

3
In [44]:

n=int(input("Enter the number of elements in the array :"))


i=0
flag = 0
a=[i for i in range(n)]
for i in range(0,n):
a[i]=int(input("Enter the {} element of the array :".format(i+1)))
for i in range(0,n):
print (a[i])
key=int(input("Enter the Key element to be searched"))
for i in range(0,n):
if a[i]==key:
print ("Key element found at",i+1,'Position')
flag = 1
break
if flag == 0:
print("Key element not found !!!")

Enter the number of elements in the array :3


Enter the 1 element of the array :33
Enter the 2 element of the array :33
Enter the 3 element of the array :33
33
33
33
Enter the Key element to be searched33
Key element found at 1 Position

4
In [45]:

n=int(input("Enter the number of elements in the array :"))


i=0
flag = 0
a=[i for i in range(n)]
for i in range(0,n):
a[i]=int(input("Enter the {} element of the array :".format(i+1)))
for i in range(0,n):
print (a[i])
key=int(input("Enter the Key element to be searched"))
for i in range(0,n):
if a[i]==key:
print ("Key element found at",i+1,'Position')
flag = 1
break
if flag == 0:
print("Key element not found !!!")

Enter the number of elements in the array :5


Enter the 1 element of the array :3
Enter the 2 element of the array :4
Enter the 3 element of the array :5
Enter the 4 element of the array :22
Enter the 5 element of the array :77
3
4
5
22
77
Enter the Key element to be searched5555
Key element not found !!!

Alternative Way:

In [2]:

n =int(input("Enter the value of n: "))


l =[int(x) for x in input("Enter {0} numbers : ".format(n)).split()]
key =int(input("Enter an item to be check in the list : "))
pos =-1
for i in range(n):
if(l[i]==key):
pos = i
break
if(pos!=-1):
print("The element {0} is present at the index of {1} in the given list".
format(key,pos))
else:
print("The element {0} is not present in the given list".format(key))

Enter the value of n: 5


Enter 5 numbers : 3 6 9 4 5
Enter an item to be check in the list : 5
The element 5 is present at the index of 4 in the given list

5
In [4]:

n =int(input("Enter the value of n: "))


l =[int(x) for x in input("Enter {0} numbers : ".format(n)).split()]
key =int(input("Enter an item to be check in the list : "))
pos =-1
for i in range(n):
if(l[i]==key):
pos = i
break
if(pos!=-1):
print("The element {0} is present at the index of {1} in the given list".
format(key,pos))
else:
print("The element {0} is not present in the given list".format(key))

Enter the value of n: 5


Enter 5 numbers : 7 77 77777 777 7777777
Enter an item to be check in the list : 7777
The element 7777 is not present in the given list

2. Binary Search Technique:

Binary search is another simple searching method.


To implement binary search method, the elements of the list must be in sorted order. So you can apply
any one of the sorting technique before using the binary search (for example bubble sort).
Biary Search method make use of divide and conquer strategy.

Procedure:

Binary search algorithm works on the principle of divide and conquer. For this algorithm to work properly,
the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection.
If a match occurs, then the index of item is returned.
If the middle item is greater than the item, then the item is searched in the sub-array to the left of the
middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the sub-array reduces to zero.

How Binary Search Works?

For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the process of
binary search with a pictorial example. The following is our sorted array and let us assume that we need to
search the location of value 31 using binary search.

First, we shall determine half of the array by using the below formula −

6
mid = low + (high - low) / 2

Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value
at location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted array, so we
also know that the target value must be in the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.

low = mid + 1

mid = low + (high - low) / 2

Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

The value stored at location 7 is not a match, rather it is less than what we are looking for. So, the value must
be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

7
We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.

Advantage:

Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.

Disadvantage:

This algorithm requires the list to be sorted,then only this method is applicable.

Python program to implement Binary search technique.

8
In [2]:

def binary_search(a,n,key):
low=0
high=n-1
while(low<=high):
mid=int((low+high)/2)
if(key==a[mid]):
return mid
elif(key<a[mid]):
high=mid-1
else:
low=mid+1
return -1

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


a=[i for i in range(n)]
for i in range(0,n):
a[i]=int(input("Enter the {} element of the array :".format(i+1)))
k=int(input("Enter the key element to be searched :"))
position=binary_search(a,n,k)
if(position!=-1):
print ("Key element found at ",(position))
else:
print ("Key element not found !!!")

Enter the number of elements : 5


Enter the 1 element of the array :23
Enter the 2 element of the array :45
Enter the 3 element of the array :67
Enter the 4 element of the array :79
Enter the 5 element of the array :90
Enter the key element to be searched :79
Key element found at 3

9
In [1]:

def binary_search(a,n,key):
low=0
high=n-1
while(low<=high):
mid=int((low+high)/2)
if(key==a[mid]):
return mid
elif(key<a[mid]):
high=mid-1
else:
low=mid+1
return -1

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


a=[i for i in range(n)]
for i in range(0,n):
a[i]=int(input("Enter the {} element of the array :".format(i+1)))
k=int(input("Enter the key element to be searched :"))
position=binary_search(a,n,k)
if(position!=-1):
print ("Key element found at ",(position))
else:
print ("Key element not found !!!")

Enter the number of elements : 5


Enter the 1 element of the array :11
Enter the 2 element of the array :12
Enter the 3 element of the array :13
Enter the 4 element of the array :14
Enter the 5 element of the array :15
Enter the key element to be searched :100
Key element not found !!!

How Linear search is different from Binary search?

Linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are
looking for.
A binary search starts in the middle of a sorted array, and determines which side (if any) the value you
are looking for is on.

10
Sorting Techniques:

Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a
particular order. Most common orders are numerical or lexicographical orders.

The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is
stored in a sorted manner.

Sorting is also used to represent data in more readable formats.

Below we see five such sorting techniques implementations in python.

1. Selection Sort
2. Bubble Sort

1.Selection Sort:

Selection sort is also known as push-down sorting. As the name suggests the first element of the list is
selected. It is compared with all the elements. If any element is found to be lesser than the selected element,
these two are interchanged. This procedure is repeated till all the elements in the list are sorted.

11
12
Advantages:

The main advantage of the selection sort is that it performs well on a small list.
Because it is an in-place sorting algorithm, no additional temporary storage is required beyond whatis
needed to hold the original list.
Its performance is easily influenced by the initial ordering of the items before the sorting process.

Disadvantages:

The primary disadvantage of the selection sort is its poor efficiency when dealing with a huge list of
items.
The selection sort requires n-squared number of steps for sorting 'n' elements.

Python program to implement Selection Sort technique:

In [3]:

def selectionSort(a):
for i in range(len(a)):
least=i
for k in range(i+1,len(a)):
if a[k]<a[least]:
least=k
temp=a[least]
a[least]=a[i]
a[i]=temp

a=[50,30,10,20,40,70,60]
print ("Original list",a)
selectionSort(a) # Calling to the function
print("Selection Sort:",a)

Original list [50, 30, 10, 20, 40, 70, 60]


Selection Sort: [10, 20, 30, 40, 50, 60, 70]

Alternative Way:

13
In [6]:

a =list(map(int,input("Enter list Elements: ").split()))


print("Before sorting the elements in the list are: ",a)
for i in range(0,len(a)-1,1):
min = i
for j in range(i+1,len(a),1):
if(a[j]<a[min]):
min = j
temp = a[min]
a[min] = a[i]
a[i] = temp
print("After sorting the elements in the list are: ",a)

Enter list Elements: 10 4 23 65 42 33


Before sorting the elements in the list are: [10, 4, 23, 65, 42, 33]
After sorting the elements in the list are: [4, 10, 23, 33, 42, 65]

In [7]:

a =list(map(int,input("Enter list Elements: ").split()))


print("Before sorting the elements in the list are: ",a)
for i in range(0,len(a)-1,1):
min = i
for j in range(i+1,len(a),1):
if(a[j]<a[min]):
min = j
temp = a[min]
a[min] = a[i]
a[i] = temp
print("After sorting the elements in the list are: ",a)

Enter list Elements: -23 -45 1 2 -77 55


Before sorting the elements in the list are: [-23, -45, 1, 2, -77, 55]
After sorting the elements in the list are: [-77, -45, -23, 1, 2, 55]

2. Bubble Sort:

This is the simplest and oldest sorting technique when compared with all the other sorting techniques.
It is also called as exchange sort.
In this sorting technique the adjacent elements are compared and interchanged if necessary.

Procedure:

14
1. Compare first and second elements. If the first element is greaterthan the second element, then
interchange these two elements.
2. Compare second and third elements. If the second element is greater than third element then make an
interchange.
3. The process is repeated till the last and second last element is compared and swapped if necessary.

This completes the first pass. At the end of the first pass, the largest element will get its exact final position
i.e., it occupies the last position.

The step-1 to step-3 are repeated n-1 times for the elements between 1 to n-1 because the nth element is
already sorted.

After completion of n-1 passes, the list is in sorted order.

Advantages:

It is relatively easy to write and understand.


Straight forward approach.
Works well for smallest list of elements.
Performance is good for nearly sorted list.

Disadvantages:

It runs slowly and hence it is not efficient, because Even if the elements are sorted, n-1 iterations are
required to sort.
It is not used for sorting the list of larger size.
It is insufficient algorithm because the number of iterations increases with increase in number of
elements to be sorted.

15
Python program to implement Bubble Sort technique:

In [1]:

a = list(map(int,input("Enter list Elements: ").split()))


print("Before sorting the elements in the list are: ",a)
for i in range(0,len(a)-1,1):
for j in range(0,len(a)-1-i,1):
if(a[j]>a[j+1]):
temp = a[j]
a[j] = a[j+1]
a[j+1]= temp
print("After sorting the elements in the list are: ",a)

Enter list Elements: 2 3 11 55 33 -6


Before sorting the elements in the list are: [2, 3, 11, 55, 33, -6]
After sorting the elements in the list are: [-6, 2, 3, 11, 33, 55]

In [2]:

a = list(map(int,input("Enter list Elements: ").split()))


print("Before sorting the elements in the list are: ",a)
for i in range(0,len(a)-1,1):
for j in range(0,len(a)-1-i,1):
if(a[j]>a[j+1]):
temp = a[j]
a[j] = a[j+1]
a[j+1]= temp
print("After sorting the elements in the list are: ",a)

Enter list Elements: -666 -333 -5 0 -66 1 4 6 3


Before sorting the elements in the list are: [-666, -333, -5, 0, -66, 1,
4, 6, 3]
After sorting the elements in the list are: [-666, -333, -66, -5, 0, 1,
3, 4, 6]

16
Tasks

Exercise 1: Write a Python function linear_search() for a linear searching.


Tips: print(linear_search([4,3,5,1,6,77,43,10],1)) should provide the output of (True, 3)

Exercise 2: Write a Python function binary_search() for a binary searching.

Tips: print(binary_search([6,7,8,10,11], 6)) should provide the output of True


print(binary_search([6,7,8,10,11], 4)) should provide the output of False

24

You might also like