x = 1 y = 100 x,y = y,x print(x, y)
def sort_bubble(list): is_change = True while is_change: is_change = False for i in range(len(list)-1): if list[i] > list[i+1]: list[i],list[i+1] = list[i+1],list[i] is_change = True
list = [1,3,9,2,0,6,4,7,5,3] sort_bubble(list) list
def sort_bubble2(list): # don't compare values at the end of the list - they are already sorted max_index = len(list) - 1 for max_not_sorted_index in range(max_index,0,-1): is_change = False for i in range(max_not_sorted_index): if list[i] > list[i+1]: list[i],list[i+1] = list[i+1],list[i] is_change = True if not is_change: break
list = [1,3,9,2,0,6,4,7,5,3] sort_bubble2(list) list
import time
import random
#declarations
max_limit = 10000
my_list1 = [random.randint(0, max_limit) for i in range(max_limit)]
my_list2 = my_list1.copy()
# functions
def sort_bubble(list):
is_change = True
while is_change:
is_change = False
for i in range(len(list)-1):
if list[i] > list[i+1]:
list[i],list[i+1] = list[i+1],list[i]
is_change = True
def sort_bubble2(list):
# don't compare values at the end of the list - they are already sorted
max_index = len(list) - 1
for max_not_sorted_index in range(max_index,0,-1):
is_change = False
for i in range(max_not_sorted_index):
if list[i] > list[i+1]:
list[i],list[i+1] = list[i+1],list[i]
is_change = True
if not is_change:
break
# checking time - case sort_bubble
start = time.time()
sort_bubble(my_list1)
stop = time.time()
print(f'Sorting duration for function sort_bubble: {stop - start}')
# checking time - case sort_bubble2
start = time.time()
sort_bubble2(my_list2)
stop = time.time()
print(f'Sorting duration for function sort_bubble2: {stop - start}')