Professional Documents
Culture Documents
CSA Lab 4
CSA Lab 4
LAB # 04
Sorting Algorithm
OBJECTIVE
THEORY
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.
Below we see 3 such implementations of sorting in python.
Bubble Sort
Insertion Sort
Selection Sort
Bubble Sort:
Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an
array with n number of elements. Bubble Sort compares all the element one by one and sort them based
on their values.
Selection Sort:
Selection sort is conceptually the simplest sorting algorithm. This algorithm will first find the smallest
element in the array and swap it with the element in the first position, then it will find the second smallest
element and swap it with the element in the second position, and it will keep on doing this until the entire
array is sorted.
It is called selection sort because it repeatedly selects the next-smallest element and swaps it into the right
place.
Insertion Sort:
Insertion sort is one of the simplest sorting algorithms for the reason that it sorts a single element at a
particular instance. It is not the best sorting algorithm in terms of performance, but it's slightly more
efficient than selection sort and bubble sort in practical scenarios. It is an intuitive sorting technique.
EXERCISE:
A. Create a file named lab4.py. Write the following code in the file. Execute it and show the output.
(You can use the Snipping Tool to take a snapshot of your output window).
1. Code:
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))
Output:
2. Code:
def insertion_sort(list1):
for i in range(1, len(list1)):
value = list1[i]
j=i-1
while j >= 0 and value < list1[j]:
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
list1 = [10, 5, 13, 8, 2]
print("The unsorted list is:", list1)
print("The sorted list1 is:", insertion_sort(list1))
Output:
B. Point out the errors, if any, in the following Python programs. (also write the correct program in code
box)
1. Code:
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A(j):
min_idx = j
Corrected code:
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print ("Sorted array")
Sorted_3 = []
for i in range(len(A)):
Sorted_3.append(A[i])
print(Sorted_3)
2. Code:
import time
start = time,time()
for i in range(10):
print(i)
time.sleep(1)
end = time.time[]
print(f"Runtime of the program is {end - start}")
Output:
Corrected code:
import time
start = time.time()
for i in range(10):
print(i)
time.sleep(1)
end = time.time()
print(f"Runtime of the program is {end - start}")
Code:
# Optimize the bubble sort implementation using Boolean flags.
# An optimized version of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to
# n-i-1. Swap if the element
# found is greater than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# IF no two elements were swapped
# by inner loop, then break
if swapped == False:
break
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted Array :")
print(arr)
bubbleSort(arr)
sorted_1 = []
print ("Sorted array :")
for i in range(len(arr)):
sorted_1.append(arr[i])
print(sorted_1)
# This code is contributed by Abdul Samad
output:
Code:
import time
start=time.time()
def bubbleSort(arr):
n = len(arr)
for i in range(n):
# swap loop
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [5, 7, 4, 6, 9, 1, 2, 10]
bubbleSort(arr)
print ("Sorted array is: ")
Sorted_1 = []
for i in range(len(arr)):
Sorted_1.append(arr[i])
print(Sorted_1)
end=time.time()
print(f"runtime is {end-start}")
Output: