I’m trying to implement a Bubble Sort algorithm. As it says here, the “Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.”
Visual Representation
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 )
So far, I have been able to identify which element is greater than the other in steps of two. Once I’ve done that, I am having some trouble swapping those elements.
Currently, I have something like this.
Code
def bubbleSort(array): for i in range(len(array)-1): if array[i] > array[i+1]: #My attempt of switching the two elements in a list array[i+1],array[i] = array[i],array[i+1] return array print(bubbleSort([5,1,4,2,8]))
Unfortunately, due to my incorrect logic, I did not get a sorted list.
output
[1, 4, 2, 5, 8]
desired output
[1 ,2 ,4 ,5 ,8]
What am I doing wrong here, why is it not sorting correctly and what can I do to fix this problem? A detailed explanation along with the provided code would be greatly appreciated.
Advertisement
Answer
What you wrote is correct but incomplete. You have just done the first pass.
All you need to do is to run all the other passes by modifying your code to:
def bubbleSort(array): for j in range(len(array)): for i in range(len(array)-1): if array[i] > array[i+1]: array[i+1],array[i] = array[i],array[i+1] return array print(bubbleSort([5,1,4,2,8]))
You can go through this article here for a better understanding.