Program for Bubble sort using Python

by | Apr 23, 2021 | Python Programs

Home » Python » Python Programs » Program for Bubble sort using Python

Introduction

The task is to sort the array elements using bubble sort.

Program for Bubble sort using Python

Program

def sort(ip_arr):
    length = len(ip_arr)
    for i in range(length - 1):
        for j in range(0, length-i-1):
            if ip_arr[j] > ip_arr[j+1]:
                ip_arr[j], ip_arr[j+1] = ip_arr[j+1], ip_arr[j]
       
ip_arr = [12, 7, 8, 21]
print("Input array is: ", ip_arr)
sort(ip_arr)
print("The sorted array is ")
for i in range(len(ip_arr)):
    print("%d" %ip_arr[i])

Output

Program for Bubble sort using Python using Python Output

Explanation

The first element is picked and checked against each element in the array and swapped if the elements are in wrong order.

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author