Q. Consider the following lists:

List 1:

2

3

5

7

11


List 2:

11

7

5

3

2


If the lists are sorted using Insertion sort then which of the lists List1 or List 2 will make the minimum number of comparisons? Justify using diagrammatic representation.


Answer :-

List 1 is sorted list.


2

3

5

7

11


List 2 required four steps:-


11

7

5

3

2


7

11

5

3

2


5

7

11

3

2


3

5

7

11

2


2

3

5

7

11

So for List 1 take minimum number of comparisons.

If you want to run then copy the following code:-


lst =  [11,7,5,3,2]
n= len(lst)
for i in range(n):
    temp = lst[i]
    j = i-1
    while j >=0 and temp< lst[j] :
        lst[j+1] = lst[j]
        j = j-1
    lst[j+1] = temp
    print(lst)

Post a Comment

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

Previous Post Next Post