| by Arround The Web | No comments

Bubble sort python

Bubble Sort” is an algorithm in Python that is used to put a group of numbers in order from smallest to largest. The bubble sort algorithm is a straightforward method that can be easily comprehended and executed. It is a good choice for beginners/newbies who are learning about sorting algorithms.

This blog will present a detailed guide on implementing Bubble Sort in Python using numerous examples.

This article discusses/examines the below topics:

What is Python Bubble Sort?

Bubble sort is a way to sort things by comparing two things next to each other and switching them until they are in the right order. If they are already in the correct sequence, nothing happens. The bubble sort algorithm is an uncomplicated way to sort things in Python.

Python Bubble Sort Working

The straightforward sorting algorithm “Bubble Sort” operates by repeatedly comparing adjacent items and changing them if they are in the incorrect sequence. The algorithm commences at the onset of the array and proceeds to compare the initial two elements. If the first item/element is greater than the second element/item, the two elements are changed. Then, the algorithm proceeds to the next two items and repeats the cycle. This keeps going until we reach the array end.

Algorithm / Pseudo Code for Bubble Sort

function(array)
  for i  rightvalue
      swap leftvalue and rightvalue
end function

How to Implement Python Bubble Sort?

Based on the bubble sort algorithm, the following custom function code is used to implement bubble sort in Python:

def bubble_sort(arr):
    for i in range(len(arr)):
        for j in range(0, len(arr) - i - 1):
            if arr[j] > arr[j + 1]:
                temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp

data = [-5, -2, 10, 21, -9]
bubble_sort(data)
print('Array Sorted in Ascending Order:\n')
print(data)

In the above code:

  • The function called “bubbleSort()” is defined by taking an array as input.
  • The function operates by repeatedly comparing adjoining elements/items and switching them if they are in the incorrect sequence.
  • Inside the function, the nested loops are initialized.
  • The function has two loops that go through the array. The first loop starts from the first element, and the second loop starts from the beginning and goes up to the element before the last one.
  • For each iteration of the second loop, the function compares the present items with the next item.
  • If the present item/element is larger than the next item, the two items are swapped.
  • The “temp” variable is used to temporarily store the value of the current element. This is needed because the function has to exchange the values of two elements, but it can’t do it directly without replacing the value of the following element.
  • Lastly, the function “bubble_sort()” takes an array of “data” as an argument and sorts an array.

Output

The array has been arranged in increasing order.

Optimization of Bubble Sort Algorithm When Array Already Sorted

The algorithm checks all the items even if they are already in order. This makes it slower. To make it faster, we can add a new variable called “swapped“. If items are swapped, swapped becomes “True”. If not, it is set to “False”. After each check, if the swap is false, it means the items are already sorted, and we do not need to check again. This makes the algorithm faster and better. Here is an example code that demonstrates this process:

def bubble_sort(arr):
    n = len(arr)
    swapped = False
   
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
                swapped = True
       
        if not swapped:
            break
arr = [54, 44, 15, 22, 32, 21, 90]
bubble_sort(arr)
print("Sorted array:", arr)

In the above code:

  • The function “bubble_sort()” is defined by taking an array as input.
  • The variable “n” stores the length of the array, and the variable “swapped” is a flag that sets to “False”.
  • The outer “for” loop iterates/loops through the array, starting from the first item, and the inner “for” loop iterates/loops through the array, starting from the beginning and until the last element.
  • For each iteration of the inner loop, the function compares the present item/element with the next item. If the present item is greater than the next item, the two items/elements are swapped.
  • The “swapped” flag is set to “True” if any swaps were made in the current iteration of the inner loop.
  • If the flag swapped is “False”, then the array is in order or sorted, and the outer loop breaks.
  • After defining the function, it is called on the specified array.

Output

The array has been sorted in ascending order.

Conclusion

In Python, the Bubble sort algorithm is used to sort things by comparing two things next to each other and swapping them until they are in the right order. If things are already in order, nothing happens when using the bubble sort algorithm in Python. This write-up demonstrated the “Bubble Sort” algorithm using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply