14 Nov 2022

Posted on:

26 Aug 2022

0

# Bubble Sort seems difficult

Dear sir,
Bubble Sort seems difficult for me. I am doubtful that, will I be able to perform the Bubble sort on my own. It will be helpful if you explain it in a simple way. Thanks.
Regards,
Shardul

Instructor
Posted on:

26 Aug 2022

6

Hey Shardul,

Let's take as an example the list used in the lecture, namely:

``````data = [53,76,25,98,56,42,69,81]
``````

Its length is 8. Therefore, the iterator `i` ranges from `0` to `8-1 = 7`.

Now, note the following relationship between the iterators `i` and `j`:
*For `i = 0`, `j` ranges from `0` to `8-0-1 = 7` exclusive (therefore, from `0` to `6`)
*For `i = 1`, `j` ranges from `0` to `8-1-1 = 6` exclusive (therefore, from `0` to `5`)
*For `i = 2`, `j` ranges from `0` to `8-2-1 = 5` exclusive (therefore, from `0` to `4`)
*For `i = 3`, `j` ranges from `0` to `8-3-1 = 4` exclusive (therefore, from `0` to `3`)
*For `i = 4`, `j` ranges from `0` to `8-4-1 = 3` exclusive (therefore, from `0` to `2`)
*For `i = 5`, `j` ranges from `0` to `8-5-1 = 2` exclusive (therefore, from `0` to `1`)
*For `i = 6`, `j` ranges from `0` to `8-6-1 = 1` exclusive (therefore, from `0` to `0`)
*For `i = 7`, `j` ranges from `0` to `8-7-1 = 0` exclusive (we don't enter the second for-loop).

The purpose of the first `for`-loop is to loop through the whole list. The purpose of the second `for`-loop is to loop through the unsorted part of the list. Below, I have modified Giles' code by adding a couple of `print`-statements to guide you through the algorithm:

``````data_copy = data[:]

for i in range(len(data_copy)):

for j in range(0, len(data_copy)-i-1):
print(f'i: {i}')
print(f'j: {j}')

print(f'{data_copy[j]}, {data_copy[j+1]}')
if data_copy[j] > data_copy[j+1]:
data_copy[j], data_copy[j+1] = data_copy[j+1], data_copy[j]
print(f'Entered the if-statement and swapped the numbers: {data_copy}\n')
else:
print(f'So far, the list is sorted: {data_copy}\n')

print(f'\n{data_copy}')
``````

Note that the list is being sorted from the back to the front, that is, pushing the biggest numbers towards the end of the list, leaving the front unsorted.

Hope this helps! Let me know if something remains unclear.

Kind regards,
365 Hristina

Posted on:

14 Nov 2022

3

HI  Shardul you can install Thonny it will help to understand complex code such as this one here is the link to (https://thonny.org/) just write the code copy and paste into thonny and then click on the debug current script it will show step by step how the code is exactly executed pls feel free to ask if you face any problem regarding installation or how to use it
thanks
fazal rahim