You are on page 1of 6

Computer System Algorithm (MCS-205) SSUET/QR/114

LAB # 04

Sorting Algorithm
OBJECTIVE

To implement sorting algorithm,


1. Bubble Sort.
2. Selection Sort.
3. Insertion Sort.

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.

Complexity Analysis of Bubble Sort:


In the worst case scenario (when the list is in reverse order), this algorithm would have to swap every
single item of the array. Our swapped flag would be set to True on every iteration.
Therefore, if we have n elements in our list, we would have n iterations per item - thus Bubble Sort's time
complexity is O(n^2).

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.

Complexity Analysis of Bubble Sort:


We can easily get the time complexity by examining the for loops in the Selection Sort algorithm. For a
list with n elements, the outer loop iterates n times.
The inner loop iterates n-1 when ‘i’ is equal to 1, and then n-2 as ‘i’ is equal to 2 and so forth.
The amount of comparisons is (n - 1) + (n - 2) + ... + 1, which gives Selection Sort a time complexity of
O(n^2)

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 1 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

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.

Complexity Analysis of Bubble Sort:


In the worst case scenario, an array would be sorted in reverse order. The outer for loop in Insertion Sort
function always iterates n-1 times.
In the worst case scenario, the inner for loop would swap once, then swap two and so forth. The amount
of swaps would then be 1 + 2 + ... + (n - 3) + (n - 2) + (n - 1) which gives Insertion Sort a time complexity
of O(n^2).

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:

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 2 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

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

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)

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 3 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

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:

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 4 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

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}")

C. Optimize the bubble sort implementation using Boolean flags.

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

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 5 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

output:

D. identify the best sorting algorithm using time library.

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:

Lab 04: Sorting Algorithm


Name: Tanzeel Ur Rehman 6 Roll no: BMCS22S-002

You might also like