In this example, we will learn how to implement the bubble sorting in Python.
The bubble sorting method is very easy to implement though it is not highly efficient. Here we take an unsorted list of 4 elements as input to explain the implementation procedures.
- Start with the first two elements and sort them in ascending order by comparing which item is greater.
- Compare the second and third element to check which one is greater, and sort them in ascending order.
- Compare the third and fourth element to check which one is greater, and sort them in ascending order.
- Repeat steps 1–3 until no more swaps are required.
#! /usr/bin/env python3 # -*- coding: utf-8 -*- Length = int(input('Please input the num of elements: ')) # input the list from terminal List =  for i in range(Length): print('please input element-%d'%(i+1)) tmp = input() List.append(tmp) # Sort for i in range(Length-1): for j in range(i+1, Length): if List[i] > List[j]: List[i],List[j] = List[j],List[i] print("Sorting Results:") print(List)
please input the num of elements: 8 please input element-1 3 please input element-2 44 please input element-3 55 please input element-4 11 please input element-5 23 please input element-6 12 please input element-7 15 please input element-8 50 Sorting Results: ['11', '12', '15', '23', '3', '44', '50', '55']