Unit 1 - Sorting algorithm

 CBSE Revision Notes

Class-11 Computer Science (New Syllabus)
Unit 1: Programming and Computational Thinking (PCT-1)


Sorting algorithm

Sorting:
Bubble sort:

list = [74, 23, 14, 10, 99, 5, 90]

count=0

n=len(list)
# Traverse through all array elements

for i in range(0,n):
# Last i elements are already in place

for j in range(0, n-i-1):
# traverse the list from 0 to n-i-1
# Swap if the element found is greater
# than the next element

if list[j] > list[j+1] :

count+=1

list[j], list[j+1] = list[j+1], list[j]

print ("Sorted list is:")

for i in range(len(list)):

print (list[i])

print("Total number of operations while sorting the list is ",count)

Insertion Sort:
list = [16, 19, 11, 15, 10, 12, 14]

count=0
#We are iterating over the list

for i in list:

j = list.index(i)
#Index of the current element is positive. This means that the element at the index of ‘j’ is not the first element and we need to compare the values.

while j>0:
#These two elements are not in order. We need to swap them. else The elements are in order, we can break the while loop.

if list[j-1] > list[j]:
#counting number of steps

count+=1
#swap

list[j-1],list[j] = list[j],list[j-1]

else:

#in order

break

j = j-1

print("List after sort")

print (list)

print("Total number of operations while sorting the list is ",count)