0% found this document useful (0 votes)
107 views13 pages

DSA Lab 4

The document discusses three sorting algorithms: bubble sort, insertion sort, and selection sort. It provides pseudocode and Python code examples for each algorithm. Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order until fully sorted. Insertion sort maintains a sorted sub-list, inserting new elements in the correct place. Selection sort divides the list into sorted and unsorted parts, selecting the minimum element from unsorted and inserting it into sorted. All three algorithms have a time complexity of O(n^2) for large data sets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views13 pages

DSA Lab 4

The document discusses three sorting algorithms: bubble sort, insertion sort, and selection sort. It provides pseudocode and Python code examples for each algorithm. Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order until fully sorted. Insertion sort maintains a sorted sub-list, inserting new elements in the correct place. Selection sort divides the list into sorted and unsorted parts, selecting the minimum element from unsorted and inserting it into sorted. All three algorithms have a time complexity of O(n^2) for large data sets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

LAB 04

SORTING TECHNIQUES USING


PYTHON

STUDENT NAME ROLL NO SEC

SIGNATURE & DATE

MARKS AWARDED:

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING


SCIENCE (NUCES) KARACHI

Prepared by: Engr. Syed Asim Mahmood Summer 2022


[SORTING TECHNIQUES USING PYTHON] LAB: 04

Lab Session 04: SORTING TECHNIQUES USING PYTHON


OBJECTIVES:
a) Implementing Bubble sort techniques to arrange a list of integers in ascending order.
b) Implementing Insertion sort techniques to arrange a list of integers in ascending order.
c) Implementing Selection sort techniques to arrange a list of integers in ascending order.

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.

Sorting include fallowing types:


1. Bubble sort 4. Quick sort
2. Insertion sort 5. Merge sort
3. Selection sort

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.

National University of Computer & Emerging Sciences, Karachi Page | 1


LAB: 04 [SORTING TECHNIQUES USING PYTHON]

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.

1 4 2 5 8 Compare 4 and 2, swap since 4 > 2


1 2 4 5 8 Compare 4 and 5, no swap.
1 2 4 5 8 Compare 5 and 8 and no swap.
Third Pass
1 2 4 5 8 Compare the first two elements and no swap.
1 2 4 5 8 Compare 2 and 4, no swap.
1 2 4 5 8 Compare 4 and 5, no swap.
1 2 4 5 8 Compare 5 and 8, no swap.
Fourth Pass
1 2 4 5 8 Compare the first two elements and no swap.
1 2 4 5 8 Compare 2 and 4, no swap.
1 2 4 5 8 Compare 4 and 5, no swap.
1 2 4 5 8 Compare 5 and 8, 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]

Page | 2 National University of Computer & Emerging Sciences, Karachi


[SORTING TECHNIQUES USING PYTHON] LAB: 04

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

This is an in-place comparison-based sorting algorithm. Here, a sub-list is


maintained which is always sorted. For example, the lower part of an array is maintained
to be sorted. An element which is to be 'inserted in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.

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.

National University of Computer & Emerging Sciences, Karachi Page | 3


LAB: 04 [SORTING TECHNIQUES USING PYTHON]

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

It is a simple sorting algorithm. This sorting algorithm is an in-place comparison


based algorithm in which the list is divided into two parts, the sorted part at the left end
and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted
part is the entire list.

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.

Compares the first two elements 14 and 33 and


14 33 27 10 35 19 42 44 these element are already in ascending order.
Now 14 is in sorted sub-list.
Compare 33 with 27 and 33 is not in correct
14 33 27 10 35 19 42 44
position. So swap 33 with 27.
14 27 33 10 35 19 42 44 Now we have 14 and 27 in the sorted sub-list.
14 27 33 10 35 19 42 44 Next compare 33 with 10.
10 14 27 33 35 19 42 44 Compare 27 with 10 and 14 with 10. Insert 10
in the proper place.

National University of Computer & Emerging Sciences, Karachi


Page | 4
[SORTING TECHNIQUES USING PYTHON] LAB: 04

10 14 27 33 35 19 42 44 Compare 33 and 35, no swap.


10 14 27 33 35 19 42 44 Compare 35 with 19
10 14 27 33 35 19 42 44 Compare 33 with 19, 27 with 19,
10 14 19 27 33 35 42 44 Compare 35 with 42, no swap.

10 14 19 27 33 35 42 44 Compare 42 with 44, no swap.

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]

print("\t \t INSERTION SORT \n \


n") print("Enter the numbers in to
list")
x = [int(x) for x in
input().split()] selection_sort(x)
print("The sorted list is", x)

National University of Computer & Emerging Sciences, Karachi


Page | 5
LAB: 04 [SORTING TECHNIQUES USING PYTHON]

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.

4. Formulate a program to sort N names using selection sort.

5. Write a program to sort N employee records based on their salary using insertion sort.

6. A class contains 50 students who acquired marks in 10 subjects write a program to


display top 10 students roll numbers and marks in sorted order by using bubble sorting
technique.

Page | 6 National University of Computer & Emerging Sciences, Karachi


[SORTING TECHNIQUES USING PYTHON] LAB: 04

Lab Report:
(It is recommended to write Lab Report in bullet Form)

National University of Computer & Emerging Sciences, Karachi Page | 7


LAB: 04 [FALL 2021 - DSA LAB] [SORTING TECHNIQUES USING PYTHON]

Student Name(s): Roll:


Section:

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:

Page | 8 National University of Computer & Emerging Sciences, Karachi


Q1
def bubble_sort(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]
print("\n\n", 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)
bubble_sort(list)

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)

Bubble_Sort(list, list2, list3)

You might also like