M
M
Muriam2019-04-04 11:51:28
Python
Muriam, 2019-04-04 11:51:28

How to count the number of comparisons and permutations in bubble sort?

from random import randint

arr = [randint(1, 100) for _ in range(10)]

def bubble_sort():
    for i in range(9):
        for j in range(9 - i):
          #comparison += 1;                                # инкремент сравнений
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
              #transfer += 1;                                 # инкремент пересылок

        
print('original array\n', *arr)
bubble_sort()    
print('bubble sort\n', *arr)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2019-04-04
@Muriam

Set the variables you use inside the function as global variables and output them.

from random import randint
comparison = 0
transfer = 0

arr = [randint(1, 100) for _ in range(10)]

def bubble_sort():
    global comparison
    global transfer
    for i in range(9):
        for j in range(9 - i):
            comparison += 1
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                transfer += 1

print('original array\n', *arr)
bubble_sort()
print('bubble sort\n', *arr)
print('comparisons: ', comparison)
print('transfers: ',transfer)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question