Program for Bubble Sort in Python

Python Program for Bubble Sort

What exactly is sorting? What’s the big deal about it? In this part, we will attempt to answer these questions.

We’ve sorted everything from books in a library to words in a dictionary to database entries and processor instructions on a number of occasions.
This means that when we sort things, we must first determine the criteria by which we will organize the items in the sequence provided to us. For the purposes of this lesson, we’ll suppose that the criteria is a number’s value, and we’ll sort a set of numbers.

The most significant goal of sorting in computer science is to create efficient algorithms. Binary Search is a lightning-fast search algorithm that would be impossible to use in an unsorted set of objects.

On sorted data, almost all set operations are extremely fast.

Apart from creating efficient algorithms, sorting is employed when a program’s sole purpose is to sort things, such as when working with a deck of cards. As a result, sorting algorithms are one of the most important things for a programmer to understand.

Sorting algorithms are programs that reorganize a huge number of elements into a certain order, such as from highest to lowest, or vice versa, or even alphabetically.

These algorithms take an input list, process it (that is, perform operations on it), and then return a sorted list.
The importance of sorting comes from the idea that if data is kept in a sorted fashion, data searching may be greatly improved. Sorting can also be used to display data in a more legible fashion. The instances of sorting in real-life circumstances are as follows:

Telephone Directory :The telephone directory keeps track of people’s phone numbers, which are classified by their names so that they may be quickly found.

Dictionary : The dictionary organizes terms alphabetically so that searching for a specific word is simple.

Examples:

Sorting in Ascending order

Example1:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Example2:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Sorting in descending order example

Example 3:

Input:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
132 132 87 80 65 63 57 45 34 26 22 9 8 2 1

Example4:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Program for Bubble Sort in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Bubble Sort Introduction

In their Computer Science course, Bubble Sort is most likely the first sorting algorithm they learned about.

It’s very natural and simple to “translate” into code, which is vital for new software engineers who are learning how to turn their thoughts into something that can be executed on a computer. Bubble Sort, on the other hand, is one of the worst-performing sorting algorithms in all cases except when testing whether the array has previously been sorted, where it frequently beats more efficient sorting algorithms like Quick Sort.

2)Working of Bubble Sort (Brief)

Consider how the bubbles in a glass of soda climb up. The greatest/smallest element in a sequence is represented by the bubbles, and the increasing movements of the bubbles reflect how the greatest/smallest element travels to the end/beginning of the sequence.
Simply explained, we repeat the sequence numerous times, swapping numerous pairs of elements each time so that the greatest/smallest element in the sequence ends up at one of the sequence’s endpoints.

For the sake of this tutorial, we’ll use the given array and sort it in ascending order of the numbers’ values.

3)Algorithm

Below is the algorithm for Bubble Sort:

  1. Count the number of elements in total. Find out how many items there are in the provided list.
  2. Calculate the number of outer passes (n – 1) that will be required. It has a length of one less than a list.
  3. For outer pass 1, make (n – 1) inner passes. Get the value of the first element and compare it to the value of the second element. If the second value is smaller than the first, the places/positions should be swapped.
  4. Continue in this manner until you reach the outer pass (n – 1). Get the next entry in the list, then continue the process from step 3 until all of the values are in ascending order.
  5. After all passes have been completed, return the result. Return the sorted list’s results.

4)Implementation

Below is the implementation of BubbleSort:

Sorting the given list in Ascending Order:

# function which implements the bubble_sort algorithm for givenlist
def bubbleSort(givenlist):
  # finding the length of given list
    length = len(givenlist)
    # using nested for loops
    for i in range(length-1):
        for j in range(length-i-1):
          # checking if the jth element is greater than j+1 th element
            if(givenlist[j] > givenlist[j+1]):
              # if it is greater then swap the elements
                givenlist[j], givenlist[j+1] = givenlist[j+1], givenlist[j]


# given list
givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to bubbleSort function which sorts the given list
bubbleSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Sorting the given list in Descending order

Below is the implementation of BubbleSort:

# function which implements the bubble_sort algorithm for givenlist
def bubbleSort(givenlist):
  # finding the length of given list
    length = len(givenlist)
    # using nested for loops
    for i in range(length-1):
        for j in range(length-i-1):
          # checking if the jth element is less than j+1 th element
            if(givenlist[j] < givenlist[j+1]):
              # if it is greater then swap the elements
                givenlist[j], givenlist[j+1] = givenlist[j+1], givenlist[j]


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to bubbleSort function which sorts the given list
bubbleSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

5)Time Complexity

The bubble sort has an O time complexity (n^2)

The following are examples of time complexities:

Worst case scenario: the provided list is in descending order. The algorithm executes as many executions as possible, which is denoted as [Big-O]
Best case : When the provided list is already sorted, this is the best case scenario. The algorithm executes the fewest number of times possible, which is denoted as [Big-Omega]? (N)
Average Case :When the list is in random order, this is the average situation. [Big-theta](n^2) is a symbol for average complexity

6)Conclusion

We learnt what sorting is and how it is used in this tutorial, then we learnt how Bubble Sort works, devised an algorithm, and implemented Bubble Sort in Python.

Bubble Sort is one of many sorting algorithms available, and while it is not the greatest, it is simple to construct. The difficulty of this approach is O(n^2), which implies that if the number of elements in the list is doubled, the time it takes to sort them with this approach will increase by four times.

As a result, this technique becomes inefficient when dealing with big amounts of data. As a coder, though, understanding Bubble Sort is critical.
Related Programs: