Python Bubble Sort


Here we discuss about a bit complex method of sorting elements using python. But, we got you covered.

The idea behind Bubble Sort is very simple, we look at pairs of adjacent elements in an array, one pair at a time, and swap their positions if the first element is larger than the second, or simply move on if it isn't. Let's look at an example and sort the array 8, 5, 3, 1, 4, 7, 9.


The below demonstration will show case the basic idea of what we accomplish from Bubble Sort.
bubble sort

The below code will implement the above algorithm.

nums = [8, 5, 3, 1, 4, 7, 9] print(nums) round = 1 while (round <= len(nums)-2): print("\n--round", round) n = 0 while (n < len(nums) - (round+1)): if (nums[n] > nums[n+1]): temp = nums[n] nums[n] = nums[n+1] nums[n+1] = temp n =n +1 print(nums) round = round + 1
Press Run to execute.

Now let's break down the code and analyze.

Define the array

nums = [8, 5, 3, 3, 4, 7, 9]

Define the list of elements(array) you want to sort.


Define the array

nums = [8, 5, 3, 3, 4, 7, 9]

Define the list of elements(array) you want to sort.








Concept & Design by Code94 Labs