Please write a function in Python that performs bubble sort.

#1
by rootacess - opened
BigCode org

Question:

Please write a function in Python that performs bubble sort.

Answer:

Here is an example of how to perform the bubble sort algorithm using Python 3:


    def bubble_sort(arr):
        n = len(arr)


        for i in range(n-1,0,-1):
            swapped = False


            # Traverse through all elements after index 'i' and swap if needed 
            for j in range (0,i):
                if arr[j] > arr[j+1]:
                    temp = arr[j] 
                    arr[j] = arr[j + 1]  
                    arr[j + 1] = temp   


                    swapped = True
            
            # If no two element were swapped by inner loop then break  
            if not swapped : 
                return
    
    array = [64, 25, 12, 22, 11]
    print("Before sorting:",array) 
    bubbleSort(array)  
    print ("After Sorting",array)
rootacess changed discussion status to closed
rootacess changed discussion status to open

Sign up or log in to comment