Answers for "How to perform Bubble sort in Python?"

21

bubble sort python

def bubbleSort(lis):
    length = len(lis)
    for i in range(length):
        for j in range(length - i):
            a = lis[j]
            if a != lis[-1]:
                b = lis[j + 1]
                if a > b:
                    lis[j] = b
                    lis[j + 1] = a
    return lis
Posted by: Guest on May-28-2020
1

How to perform Bubble sort in Python?

"""
Bubble sort sorts a list by repeatedly
swapping adjacent out-of-order values.
The process continues until the list
becomes sorted. 
"""


def bubble_sort(array):
    isSorted = False
    passes = 0
    length = len(array)
    while not isSorted:
        isSorted = True
        # perform a pass through the array
        # excluding already sorted positions
        for i in range(length-1-passes):
            if array[i] > array[i+1]:
                swap(i, i+1, array)
                # array is not sorted yet
                isSorted = False
        passes += 1
    return array


def swap(i, j, array):
    # Swap values at indexes i and j
    array[i], array[j] = array[j], array[i]


arr = [1, 9, 3, 2]
print(bubble_sort(arr))  # [1, 2, 3, 9]
Posted by: Guest on April-25-2022
1

bubble sort python

def bubble(st):
    for i in range(len(st),1,-1):
        for j in range(0,i-1):
            if st[j]>st[j+1]:
                st[j],st[j+1]=st[j+1],st[j]
            else:
                pass
    print(st)
bubble([64, 34, 25, 12, 22, 11, 90] )
Posted by: Guest on March-01-2021

Python Answers by Framework

Browse Popular Code Answers by Language