What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Bubble Sort in Python (with code)

  • Apr 25, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Bubble Sort in Python (with code)

In computer programming, there are numerous ways for "sorting", which refers to the organization of data in a particular order. Each has its own advantages and disadvantages. In this article, we will learn about Bubble Sort in Python with code and time complexity, accepting user input during the sorting process, and more.

What is Bubble Sort?

Bubble sort is a simple sorting algorithm that exchanges adjacent elements in a list until the list is sorted. The algorithm is referred to as a "bubble sort" because it ranks the smallest elements first. While it is very easy to learn for beginners and execute for small datasets, bubble sort is not appropriate for efficiently sorting large datasets. 

If two adjacent elements are not in the correct order, the bubble sort will swap them repeatedly. This means that all the individual element pairs are compared; if the first element is greater than the second, the pair is swapped, etc. That's why it is also known as the sinking sort because, in the process, the larger elements will technically "sink" to the bottom (or the end) of the list with each iteration.

Even when compared to insertion sort, the algorithm is too slow and impractical for most tasks. If the input is mostly in sort order but rarely contains some out-of-order elements that are nearly in position, this method may be useful.

The detailed, illustrative diagram is shown in the below figure:

how bubble sort works illustration

Sorting a List using Bubble Sort in Python

Using the bubble sort algorithm to organize a list in Python is straightforward. Here is the code:

def bubble_sort(a_list):

    for i in range(0,len(a_list)-1): 

        for j in range(len(a_list)-1): 

            if(a_list[j]>a_list[j+1]): 

                temp = a_list[j]

                a_list[j] = a_list[j+1] 

                a_list[j+1] = temp 

        return a_list 

a_list= [2,6,3,1,8,4] 

print("original list: ", a_list) 

print("list after sorting: ", bubble_sort(a_list)) 

 

Output:

original list: [2, 6, 3, 1, 8, 4]

list after sorting: [1, 2, 3, 4, 6, 8]

 

The preceding code defines a bubble_sort() function that accepts a_list as an argument. The function contains two for loops: the first loop iterates through the entire list, while the second loop iterates through the list and compares each pair of items during each outer loop iteration.

When the for loop reaches the end, the program will exit the loop. If the value of the first index is greater than the value of the second index, then the two indices should be exchanged. This condition is defined in the inner for loop. The function was invoked with a list as input, and after iterating through the input, it returned the sorted list.

Bubble Sort without using a Temp Variable

The temp variable is not necessary for the element swap operation. Python's syntax differs significantly from that of other languages. The following code will help you understand better:

def bubble_sort(list1): 

    for i in range(0,len(a_list)-1): 

        for j in range(len(a_list)-1): 

            if(a_list[j]>a_list[j+1]):

                a_list[j],a_list[j+1] = a_list[j+1], a_list[j] 

    return list1 

a_list= [2,6,3,1,8,4]

print("original list: ", a_list) 

print("list after sorting: ", bubble_sort(a_list))

 

Output:

original list: [2, 6, 3, 1, 8, 4]

list after sorting: [1, 2, 3, 4, 6, 8]

 

Is bubble sort in built-in Python?

Bubble sort is not built-in in any of Python's standard libraries but you can implement it will its programming language using a loop. However, there is a sorted() sorted() method in Python that makes sorting collections simple. The sorted() function uses the Timsort algorithm, which combines the finest features of merge sort and insertion sort, making it a more effective sorting method than bubble sort.

Consider the following as an illustration of how to sort a list using the sorted() function:

a_list = [2,6,3,1,8,4]

sorted_list = sorted(a_list)

print("list after sorting:", sorted_list)

 

Output:

list after sorting: [1, 2, 3, 4, 6, 8]

 

You can see that the list has been sorted in ascending order using the sort() method. Although bubble sort is not native to Python, it can be created as a user-defined method, as was demonstrated above.

For large lists, however, the built-in sorted() function or alternative efficient sorting algorithms such as quick sort, merge sort, or heap sort are strongly suggested. These algorithms outperform bubble sort in terms of time complexity and efficiency.

Bubble Sort Python with user input

This Python program allows the user to input the elements into the list. After that, the list items are organized using the bubble sort algorithm.Here is the code:

def bubble_sort(a_list):

    for i in range(0,len(a_list)-1): 

        for j in range(len(a_list)-1): 

            if(a_list[j]>a_list[j+1]): 

                temp = a_list[j] 

                a_list[j] = a_list[j+1] 

                a_list[j+1] = temp 

    return a_list 

list_a= input("Enter a list of numbers, separated by commas: ")

a_list=[int(num) for num in list_a.split(',')]

print("original list: ", a_list) 

print("list after sorting: ", bubble_sort(a_list)) 

 

Output:

Enter a list of numbers, separated by commas: 1,6,5,8,9,2

original list: [1, 6, 5, 8, 9, 2]

list after sorting: [1, 2, 5, 6, 8, 9]

 

A Nested For Loop is used in this Python program to iterate over the items in a given List. Inside the loop, we're employing an If statement to determine whether or not to use Bubble Sort, which will sort the objects in ascending order.

Bubble Sort Time Complexity

The time complexity of an algorithm is defined as the execution time as a function of the size of the input. When n is the total number of items to be sorted, bubble sort has an O(n^2) time complexity.

  • Worst Case Complexity: O(n2), if we attempt to sort in ascending order but the list is arranged in descending order, the worst-case scenario occurs.
  • Best Case Complexity: O(n), if the array is already sorted, it is unnecessary to rearrange it.
  • Average Case Complexity: O(n2), which will occur if the array's components are out of order. (neither ascending nor descending).

Advantages of Bubble Sort

The following are some benefits of the bubble sort algorithm:

  1. It is simple to comprehend what is being said.
  2. When the list is already organized or nearly sorted, the functionality is exceptional.
  3. Does not require a lot of memory space.
  4. The code for the algorithm can be written easily.
  5. The space requirements are low when compared to other classification algorithms.

Conclusion

To sum up, Bubble Sort in Python is a simple and memory-efficient algorithm for smaller lists.  It is a great method to get started with sorting algorithms and can help you understand more complex alternatives. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.