How to Implement Bubble Sorting in Python


In this example, we will learn how to implement the bubble sorting in Python.

2. Procedures

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.

Source Code

#! /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)

Output:

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']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments