DSA Lab 4
DSA Lab 4
MARKS AWARDED:
INTRODUCTION
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 in numerical or lexicographical
order.
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. Following are some of the examples of sorting in real-life scenarios −
• Telephone Directory:
The telephone directory stores the telephone numbers of people sorted by their
names, so that the names can be searched easily.
• Dictionary:
The dictionary stores words in an alphabetical order so that searching of any
word becomes easy.
A. Bubble sort:
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-
based algorithm in which each pair of adjacent elements is compared and the elements
are swapped if they are not in order.
Time Complexity
This algorithm is not suitable for large data sets as its average and worst case complexity are
of Ο (n2) where n is the number of items.
Example:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are not in order.
First Pass
5 1 4 2 8 Compare the first two elements, and swaps since 5 > 1
1 5 4 2 8 Compare 5 and 4 and swap since 5 > 4
1 4 5 2 8 Compare 5 and 2 and swap since 5 > 2
1 4 2 5 8 Compare 5 and 8 and since 5 < 8, no swap.
Second Pass
1 4 2 5 8 Compare the first two elements, and as 1 < 4, no swap.
def bubblesort(mylist):
n = len (mylist)
for i in range(0, n):
for j in range(0, n-i-1):
if mylist[j] > mylist[j+1]:
mylist[j], mylist[j+1] = mylist[j+1], mylist[j]
print("\t \t BUBBLE SORT \n \n")
print("Enter the numbers in to list")
x = [int(x) for x in input().split()]
bubblesort (x)
print("The sorted list is", x)
Output
Enter the numbers in to list
8 5 2 144 6 1
The sorted list is [1, 2, 5, 6, 8, 144]
Implementation
One more issue we did not address in our original algorithm and its improvised pseudocode,
is that, after every iteration the highest values settles down at the end of the array. Hence, the
next iteration need not include already sorted elements. For this purpose, in our
implementation, we restrict the inner loop to avoid already sorted values.
B. Insertion sort:
We continuously remove the smallest element of the unsorted segment of the list
and append it to the sorted segment
Time Complexity
The array is searched sequentially and unsorted items are moved and inserted into
the sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
its average and worst case complexity are of O(n^2), where n is the number of items.
Consider a list a = [64, 25, 12, 22, 11]
Index 0 1 2 3 4 Remarks
Find the minimum element in a[0 .. 4] and place it
List 64 25 12 22 11
at beginning.
Iteration 1 Find the minimum element in a[1 .. 4] and place
11 25 12 22 64
it at beginning of a[1 .. 4]
Iteration 2 Find the minimum element in a[2 .. 4] and place it
11 12 25 22 64
at beginning of a[2 .. 4]
Iteration 3 Find the minimum element in a[3 .. 4] and place it
11 12 22 25 64
at beginning of a[3 .. 4]
Iteration 4 11 12 22 25 64 Finally the list is sorted.
Code:
def insertion_sort(nums):
# Start on the second element as we assume the first element is sorted
for i in range(1, len ( nums ) ):
item_to_insert = nums [ i ]
# And keep a reference of the index of the previous element
j=i-1
# Move all items of the sorted segment forward if they are larger than the item to insert
while j >= 0 and nums[j] > item_to_insert:
nums [j + 1] = nums [j]
j -= 1
# Insert the item
nums [j + 1] = item_to_insert
random_list_of_nums = [9, 1, 15,
28,6] insertion_sort
(random_list_of_nums) print
(random_list_of_nums)
C. Selection sort
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.
Time Complexity
This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items. Consider an unsorted list with
8 elements.
In practice, we don't need to create a new list for the sorted elements, what we do is treat the
leftmost part of the list as the sorted segment. We then search the entire list for the smallest
element, and swap it with the first element.
Now we know that the first element of the list is sorted, we get the smallest element
of the remaining items and swap it with the second element. This iterates until the last item
of the list is remaining element to be examined.
Code:
def selection_sort(nums):
# This value of i corresponds to how many values were sorted
for i in range(len(nums)):
# We assume that the first item of the unsorted segment is the smallest
lowest_value_index = i
# This loop iterates over the unsorted items
for j in range(i + 1, len(nums)):
if nums[j] < nums[lowest_value_index]:
lowest_value_index = j
# Swap values of the lowest unsorted element with the first unsorted element
nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i]
Lab tasks
1. Formulate a program that implement Bubble sort, to sort a given list of integers in
descending order.
2. Compose a program that implement Insertion sort, to sort a given list of integers in
descending order.
3. Write a program that implement Selection sort, to sort a given list of integers in
ascending order.
5. Write a program to sort N employee records based on their salary using insertion sort.
Lab Report:
(It is recommended to write Lab Report in bullet Form)
Method: Lab reports and instructor observation during Lab sessions Outcome
Assessed:
a. Ability to conduct experiments, as well as to analyze and interpret data (P3/PLO 4).
b. Ability to function on multi-disciplinary teams (A/PLO 9).
c. Ability to use the techniques, skills, and modern engineering tools necessary for engineering
practice (P/PLO 5).
d. An ability to design a solution for an open-ended lab with appropriate considerations for public health
and safety, cultural, societal, and environmental factors. (C/PLO3)
Performance Exceeds expectation (5-4) Meets expectation (3-2) Does not meet expectation Marks
(1-0)
1. Realization of Selects relevant equipment to the Needs guidance to select relevant Incapable of selecting relevant
Experiment [a, c] experiment, develops setup equipment to the experiment and equipment to conduct the
diagrams of equipment to develop equipment connection experiment, equipment connection
connections or wiring. or wiring diagrams. or wiring diagrams.
2. Teamwork [b] Actively engages and Cooperates with other group Distracts or discourages other
cooperates with other group members in a reasonable manner. group members from conducting
members in an the experiment.
effective manner.
3. Conducting Does proper calibration of Calibrates equipment, examines Unable to calibrate appropriate
Experiment [a, c] equipment, carefully examines equipment moving parts, and operatesequipment, and equipment operation
equipment moving parts, and the equipment with minor error. is substantially wrong.
ensures smooth operation and
process.
4. Laboratory Respectfully and carefully observes Observes safety rules and procedures Disregards safety rules and
Safety Rules [a] safety rules and procedures with minor deviation. procedures.
5. Data Collection Plans data collection to achieve Plans data collection to achieve Does not know how to plan data
[a] experimental objectives, and experimental objectives, and collectscollection to achieve experimental
conducts an orderly and a complete complete data with minor error. goals; data collected is incomplete and
data collection. contain errors.
6. Data Analysis [a] Accurately conducts simple Conducts simple computations and Unable to conduct simple statistical
computations and statistical analysis statistical analysis using collected data analysis on collected data; no attempt
using collected data; correlates with minor error; reasonably correlates to correlate experimental results with
experimental results to known experimental results to known known theoretical values; incapable of
theoretical values; accounts for theoretical values; attempts to account explaining measurement errors or
measurement errors and parameters for measurement errors and parameters parameters that affect the
that affect experimental results. that affect experimental results. experimental results.
7. Design of Able to design and implement the Able to design and partially implement Unable to design the complete
Experiment [d] complete solution of open-ended the complete solution of open-ended solution of open-ended problem with
problem with safety, health and problem with safety, health and safety, health and environment related
environment related considerations. environment related considerations. considerations.
Total
Lecturer / Faculty
Signature:
Date:
Q2
def insertion_sort(list):
for i in range(1, len ( list ) ):
item_to_insert = list [ i ]
j=i-1
while j >= 0 and list[j] < item_to_insert:
list [j + 1] = list [j]
j -= 1
list [j + 1] = item_to_insert
print(list)
list = []
x = int(input("Please enter the number of items in thje list : "))
for i in range (0, x):
print("Enter the element at position ", i+1 ,": ")
y = int(input())
list.append(y)
insertion_sort(list)
Q3
def selection_sort(list):
for i in range(len(list)):
lowest_value_index = i
for j in range(i + 1, len(list)):
if list[j] < list[lowest_value_index]:
lowest_value_index = j
list[i], list[lowest_value_index] = list[lowest_value_index], list[i]
print("\t \t INSERTION SORT \n \n")
print(list)
list = []
x = int(input("Please enter the number of items in the list : "))
for i in range (0, x):
print("Enter the element at position ", i+1 ,": ")
y = int(input())
list.append(y)
selection_sort(list)
Q4
def selection_sort(list):
for i in range(len(list)):
lowest_value_index = i
for j in range(i + 1, len(list)):
if list[j] < list[lowest_value_index]:
lowest_value_index = j
list[i], list[lowest_value_index] = list[lowest_value_index], list[i]
print("\t \t INSERTION SORT \n \n")
print(list)
list = []
x = int(input("Please enter the number of names in the list : "))
for i in range (0, x):
print("Enter the name at position ", i+1 ,": ")
y = input()
list.append(y)
selection_sort(list)
Q5
def selection_sort(list, list2):
for i in range(len(list)):
lowest_value_index = i
for j in range(i + 1, len(list)):
if list[j] < list[lowest_value_index]:
lowest_value_index = j
list[i], list[lowest_value_index] = list[lowest_value_index], list[i]
list2[i], list2[lowest_value_index] = list2[lowest_value_index], list2[i]
print("\t \t INSERTION SORT \n \n")
print(list2, list)
list = []
list2 = []
a = int(input("Please enter the number of employees in the list : "))
for i in range (0, a):
b = input(("Enter the name at position {} : ".format(i+1)))
list2.append(b)
print()
c = int(input("Enter the salary of {} : ".format(b)))
list.append(c)
selection_sort(list, list2)
Q6
def Bubble_Sort(list, list2, list3):
for i in range(len(list)):
n = len(list)
for i in range(n):
for j in range (n-i-1):
if list[j]<list[j+1]:
list[j],list[j+1] = list[j+1],list[j]
list2[j],list2[j+1] = list2[j+1],list2[j]
list3[j],list3[j+1] = list3[j+1],list3[j]
print(list2, list3, list)
print("\t \t Top Ten Positions \n \n")
for x in range (3):
print ("{}. {} ({}) got {} marks".format(x+1, list2[x], list3[x], list[x]))
list = []
list2 = []
list3 = []
a = int(input("Please Enter the number of students in the class : "))
for i in range (0, a):
b = input(("Enter the name at position {} : ".format(i+1)))
list2.append(b)
d = input(("Enter the Roll number of {} : ".format(b)))
list3.append(d)
c = int(input("Enter the marks of {} : ".format(b)))
list.append(c)