# Python: Bubble sort

## Python Search and Sorting : Exercise-4 with Solution

Write a Python program to sort a list of elements using the bubble sort algorithm.

Note : According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position.

**Step by step pictorial presentation :**

**Sample Solution**:-

**Python Code:**

```
def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(nlist)
```

Sample Output:

[14, 21, 27, 41, 43, 45, 46, 57, 70]

**Flowchart: **

**Python Code Editor :**

** Contribute your code and comments through Disqus.**

**Previous:** Write a Python program for binary search for an ordered list.

**Next:** Write a Python program to sort a list of elements using the selection sort algorithm.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## Python: Tips of the Day

**Returns the symmetric difference between two lists, after applying the provided function to each list element of both:**

Example:

def tips_symmetric_difference_by(p, q, fn): _p, _q = set(map(fn, p)), set(map(fn, q)) return [item for item in p if fn(item) not in _q] + [item for item in q if fn(item) not in _p] from math import floor print(tips_symmetric_difference_by([4.2, 2.4], [4.6, 6.8],floor))

Output:

[2.4, 6.8]

**Weekly Trends**- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook