Bubble Sort Algorithm Using Python
Simple Bubble Sort Algorithm
First the question is what is bubble sort algorithm. This is one of the sorting techniques in Data Structures and Algorithms (DSA). In Bubble Sort Algorithm Technique we arrage the program in acending or decending order. In this algorithm iterations occurs until all program turn into acending or descending order (what ever we want to do). You can see below how bubble sort works in the picture below.
Diagram
Explaination
Lets take a list in python:
Iteration 1
1) Check or compare 54 and 23 as we are sorting this in acending order so 23 is smaller then 54 so both numbers swap with each other.
2) Now it will check other two numbers which are 54 and 33. now this time 33 is less than 54 so both the numbers will swap.
3) Now in this step it will swap next two numbers 54 and 15 because 15 is less than 54. and now all the list is sorted as 23, 33, 15, 54.
Iteration 2
Now in the 2nd iteration it will check full list again
1) In this step it will compare 23 and 33 as these numbers are already sorted so it will move to the next two numbers.
2) It will check 33 and 15 as 15 is less then 33. So, both numbers will swap with each other.
3) Now it will check 33 and 54 as these numbers are all ready sorted so no action will take place.
Iteration 3
Now in the 3rd iteration program will check full list again
1) It will compare 23 and 15, as 15 is less then 23 so both numbers will swap with each other.
2) Now it will check 23 and 33 both numbers are already sorted so no need to take any action.
3) Now it will check 33 and 54 as these numbers are all ready sorted so no action will take place.
Run Program
To run the following program I recommend to use this link https://www.onlinegdb.com/ Online gdb is a online free interpreter or compiler for many languages like C, C++, Python or Java etc.
Program (Python)
def BubbleSort(nlist):
for j in range(len(nlist)-1,0,-1):
for i in range(j):
if nlist[i]>nlist[i+1]:
nlist[i],nlist[i+1]=nlist[i+1],nlist[i]
nlist = [54,23,33,15]
BubbleSort(nlist)
print(nlist)
Program Explaination
We define a function in the program and call it outside the function now we take two for loops the outer loop is to gone through the whole list or checks the whole list and the inner loop contain if statement and in the if statement we are check condition that weather the first number is greater then the second number or not to understand swaping value of two places look at the simple swaping following program.
x=10
y=50
x,y=y,x
print(x,y)
In the above small program we just swap values of two variable by assigning
x=y and y=x in short we write it like x,y=y,x now you should look at the
1st program above the program explanation assume nlist[i] as x and
nlist[i+1] as y now it will be like:
#nlist[i],nlist[i+1]= nlist[i+1],nlist[i]
x,y=y,x
print(x,y)

Comments
Post a Comment