# Sort a list in ascending order using loop

‘’'Write a Python program to sort a list in ascending order using loop.
Input:- [100,10,1,298,65,483,49876,2,80,9,9213]
Output:- [1,2,9,10,65,80,100,298,483,9213,49876]

Using bubble sort
lst = [100,10,1,298,65,483,49876,2,80,9,9213]
for i in range(len(lst)):
for j in range(len(lst)-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(‘The sorted list is’, lst)
print(“*******”)‘’’ am unable to understand this code for j in range(len(lst)-i-1): what -i -1 is doing

Please format you code correctly to allow it to be more readable in the future.

Bubble sort works by itertatively going through the list, comparing pairs. It starts at the front, the 0 index and compares it with the second element, 1 index.

If the second element is less than the first, they are swapped. This process is continued, sliding this comparison of pairs across the list. Naturally, this would be perfect if the list was actually in perfect reverse order, so one final iteration, or slide is required across the list.

The len(lst) - i - 1, results in this end index. It is the position of the second index to be compared. Here is an image for reference.

This was a good example however is for java, I just liked the image

I am not going to give your exact answer here, because this appears to be homework. So here is the explanation for the image:

Starting from the beginning of the list, the first two elements are compared: 18 and 32.

Since they are in the correct order (smaller before larger), no swap is needed.

Next, 32 and -11 are compared, and since -11 is smaller than 32, a swap is performed. The list after the first comparison would look like this: [18, -11, 32, -6, -68, -2, -24].

The algorithm continues to compare adjacent elements and perform swaps if necessary. After the first iteration, the largest element (-11) would have moved to the end of the list, and the list would look like this: [18, 32, -6, -68, -2, -24, -11].In this first iteration, the largest element (-11) “bubbles” to its correct position at the end of the list.

The algorithm will then repeat this process for the remaining unsorted elements until the list is completely sorted in ascending order.

1 Like