OK, so you would never actually use this algorithm to sort a list in a high-level programming language like Python. You would probably just use the built-in sorted() function (which, by the way, uses an algorithm called Timsort). But let's do it anyway.
Let's sort this short list from descending order to ascending order using a variation of bubble sort:
Start with the first element (4).We are going to compare this first element with all the elements that come after it. So, compare the first element (4) to the second element (8), if the first element is greater than the second element (it's not), swap them.
Then, compare the first element (still 4) to the third (3), swap if necessary (it is).
Compare the first element to the fourth, swap if necessary, etc. After one run through, you will end up with this:
As you can see, this is not quit sorted yet, but we're getting there. Moving on, compare the second element (8) to the rest of the elements that come after it and swap values, if necessary.
On with the code. Start with a function bubbleSort()
that takes in one list as an argument and returns a sorted list.
def bubbleSort(nums):
We will loop through the list with a for
loop like this:
for i in range(len(nums)):
Inside this loop, we will nest another loop.
for i in range(len(nums)): for j in range(i+1, len(nums)):
Then, our test. If nums[j] (which is some number that is indexed after nums[i]) is greater than nums[i], we swap the elements.
if nums[j] < nums[i]: nums[j], nums[i] = nums[i], nums[j]
Our final code will look like this:
def bubbleSort(nums): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[j] < nums[i]: nums[j], nums[i] = nums[i], nums[j] return nums