Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

how to show comparison in bubble sort in python along with number of swaps

def bubbleSort(arr): 
    n = len(arr) 
    count = 0
  
    # Traverse through all array elements 
    for i in range(n): 
  
        # Last i elements are already in place 
        for j in range(0, n-i-1): 
            if arr[j] > arr[j+1] : 
                count = count + 1
                arr[j], arr[j+1] = arr[j+1], arr[j] 
    print(count)
  
# Driver code to test above 
arr = [64, 34, 25, 12, 22, 11] 
  
bubbleSort(arr) 

print ("Sorted array is:") 
for i in range(len(arr)): 
    print ("%d" %arr[i]),

how to show comparison in the following code, the above code displays number of swaps and sorted array

question from:https://stackoverflow.com/questions/65916453/how-to-show-comparison-in-bubble-sort-in-python-along-with-number-of-swaps

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside the bubbleSort function, you need to print the count and the current state of the array either after or before swapping. it's simple just like so:

def bubbleSort(arr): 
    n = len(arr)
    count = 0
  
    # Traverse through all array elements 
    for i in range(n): 
  
        # Last i elements are already in place 
        for j in range(0, n-i-1): 
            if arr[j] > arr[j+1] : 
                count = count + 1
                arr[j], arr[j+1] = arr[j+1], arr[j] 
                print(f"#swaps: {count}, array: {arr}") #<--- just add this

And you will get the following output:

#swaps: 1, array: [34, 64, 25, 12, 22, 11]
#swaps: 2, array: [34, 25, 64, 12, 22, 11]
#swaps: 3, array: [34, 25, 12, 64, 22, 11]
#swaps: 4, array: [34, 25, 12, 22, 64, 11]
#swaps: 5, array: [34, 25, 12, 22, 11, 64]
#swaps: 6, array: [25, 34, 12, 22, 11, 64]
#swaps: 7, array: [25, 12, 34, 22, 11, 64]
#swaps: 8, array: [25, 12, 22, 34, 11, 64]
#swaps: 9, array: [25, 12, 22, 11, 34, 64]
#swaps: 10, array: [12, 25, 22, 11, 34, 64]
#swaps: 11, array: [12, 22, 25, 11, 34, 64]
#swaps: 12, array: [12, 22, 11, 25, 34, 64]
#swaps: 13, array: [12, 11, 22, 25, 34, 64]
#swaps: 14, array: [11, 12, 22, 25, 34, 64]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...