python

Bubble Sort in Python

We can create a Python program to sort the elements of an array using bubble sort. The bubble sort algorithm is known as the simplest sorting algorithm.

In bubble sort algorithm, the array is scanned from the first to the last element. Here, the current item is compared to the next item. If the current item is greater than the next item, it is swapped. Here’s how the process works:
 

Example :


Source: Wikipedia.org

 
 

Bubble Sort in Python
# Python script for implementing Bubble Sort
 
def bubble_sort(arr):
    n = len(arr)
    # iterate through array elements 
    for i in range(n):
        for j in range(0, n-i-1):
            # swap if the element found is greater than the next
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]


# Main program to test the above code
arr = [98, 22, 15, 32, 2, 74, 63, 70]
 
bubble_sort(arr)
 
print ("Sorted array: ")
for i in range(len(arr)):
    print ("%d" %arr[i])

Output:

Sorted array:
2
15
22
32
63
70
74
98
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *