Q. (a) Carefully go through following code of Bubble Sort technique. It is creating some problem during execution. Figure out the problem and correct it.
Try writing efficient solution of the problem.
Hint. Efficient solution is error free and has less number of operation taking place
:
#arr is the list being sorted
n = len(arr)
for i in range(n):
for j in range(n):
if(arr[j] > arr[j+1])
temp = arr[1]
arr[j] = arr[j+1]
arr[j+1] = temp
for i in range(n):
print (arr[i], end = "")
(b) Find out the problem in following code of Insertion sort technique. State the problem and suggest solution for it.
:
#arr is the list being sorted
n = len(arr)
for i in range(n):
key = arr[i]
j = 1 - 1
while j >= 0 and key < arr[j] :
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = key
for i in range (n):
print(arr[i])
Answer :-
(a)
Correct Program:-
#arr is the list being sorted arr = eval(input ("Enter List :- ")) n = len(arr) for i in range(n): for j in range(n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] for i in range(n): print (arr[i], end = " ")
Output :-
Enter List :- [5,3,6,9,7,4,1,2,6,3,85,99]
1 2 3 3 4 5 6 6 7 9 85 99
>>>
Enter List :- [55,99,22,2,3,44,555,888,7466]
2 3 22 44 55 99 555 888 7466
>>>
1 2 3 3 4 5 6 6 7 9 85 99
>>>
Enter List :- [55,99,22,2,3,44,555,888,7466]
2 3 22 44 55 99 555 888 7466
>>>
(b)
Correct Program :-
#arr is the list being sorted arr = eval(input ("Enter List :- ")) n = len(arr) for i in range(n): key = arr[i] j = i - 1 while j >= 0 and key < arr[j] : arr[j+1] = arr[j] j = j - 1 else : arr[j+1] = key for i in range (n): print(arr[i], end = " ")
Output :-
Enter List :- [99,363,541,256,33,2,7874,565968]
2 33 99 256 363 541 7874 565968
>>>
Enter List :- [4554,35,69,55,47,256314]
35 47 55 69 4554 256314
>>>
2 33 99 256 363 541 7874 565968
>>>
Enter List :- [4554,35,69,55,47,256314]
35 47 55 69 4554 256314
>>>
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )