Solutions Of


Bubble Sort in Python

Bubble sort algorithm in Python:

The logic of bubble sort is as follows:

  1. Start at the beginning of the list.
  2. Compare the first two elements.
  3. If the first element is greater than the second element, swap them.
  4. Move on to the next two elements.
  5. Repeat steps 2-4 until you reach the end of the list.
  6. Repeat steps 1-5 until no more swaps are made.

The bubble sort algorithm is a simple sorting algorithm that works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. Bubble sort is not very efficient, but it is easy to understand and implement.

Python
def bubble_sort(list1):
  # Outer loop for traverse the entire list.
  for i in range(0, len(list1) - 1):
    # Inner loop for comparing adjacent elements.
    for j in range(len(list1) - 1):
      # If the current element is greater than the next element, swap them.
      if list1[j] > list1[j + 1]:
        temp = list1[j]
        list1[j] = list1[j + 1]
        list1[j + 1] = temp

  return list1

 

Here is an example of how to use the bubble sort algorithm in Python:

Python
list1 = [5, 3, 8, 6, 7, 2]

print("The unsorted list is: ", list1)

sorted_list = bubble_sort(list1)

print("The sorted list is: ", sorted_list)

This code will print the following output:

Code snippet
The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]
,

Published by