Q. Identify the number of swaps required for sorting the following list using selection sort and bubble sort and identify which is the better sorting technique with respect to the number of comparisons.

List 1:

63

42

21

9

Answer :-

Number of Swap required by Bubble sort: - 6
Number of Swap required by Selection sort: - 5

So for it is clear that Selection sort is better the bubble sort.
If you want see the number of operation then copy the code and run it:-

Bubble Sort:-


lst = [63, 42, 21, 9]
lst.sort()
numList = [63, 42, 21, 9]
n = len(numList)
a = 0
for i in range(n):
    for j in range(0, n-i-1):
        if lst == numList :
            break
        else :
            a += 1
            if numList[j] > numList[j+1] :
                numList[j], numList[j+1] = numList[j+1], numList[j]

print(numList)
print("Number of operation required :- ", a)

For Selection Sort:-


lst = [63, 42, 21, 9]
lst.sort()
list2 = [63, 42, 21, 9]
a = 0
n=len(list2)
for i in range(n):
    min = i
    for j in range(i + 1, n):
        if lst == list2 :
            break
        else :
            a += 1
            if list2[j] < list2[min]:
                min = j
    list2[min], list2[i] = list2[i], list2[min]

print(list2)
print("Number of operation required :- ", a)



Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post