# Python Data Structures and Algorithms: 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 Python skills with w3resource's quiz

## Python: Tips of the Day

**Returns the maximum value of a list, after mapping each element to a value using the provided function**

Example:

def tips_max(lst, fn): return max(map(fn, lst)) print(tips_max([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))

Output:

8

**New Content published on w3resource :**- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework