Given the function code:
def Sort(list1):
n = len(list1)
for i in range(n):
for j in range(0, n-i-1):
if list1[j] > list1[j+1] :
list1[j], list1[j+1] = list1[j+1], list1[j]
Identify the type of sort being done in the above code:
Given the function code:
def Sort(list1):
n = len(list1)
for i in range(n):
for j in range(0, n-i-1):
if list1[j] > list1[j+1] :
list1[j], list1[j+1] = list1[j+1], list1[j]
Identify the type of sort being done in the above code:
Solution
The code compares each pair of adjacent elements, list1[j] and list1[j+1], and swaps them if they are out of order. After each pass of the outer loop, the largest remaining element moves to the end of the list. This is why the inner loop runs only up to n-i-1. Repeatedly swapping adjacent elements like this is bubble sort.
Option 2: selection sort also uses nested loops, but it finds the smallest element in the unsorted part and does one swap per pass, not swaps of adjacent pairs.
Option 4: insertion sort picks one element and shifts larger elements to insert it into the sorted part on its left. It does not repeatedly swap neighbours across the whole list.
Option 3: merge sort splits the list into halves and merges them, usually with recursion, which this code does not do.
Related questions:
2025: 15 May Shift 2
2026: 29 May Shift 2
2025: 3 June Shift 2
2025: 13 May Shift 2