Answer the question
In order to leave comments, you need to log in
A problem with the random list sorter. Can you help?
Hello. I have a problem in writing a program to calculate the average value of the time spent sorting a list. Problem conditions:
For each sorting algorithm, calculate the average (it is necessary to measure 10 times) sorting execution time for 10,100,1000,10000,100000 elements. The list of elements are selected randomly. Algorithms:
1) bubble sort
To count time, use time.perf_counter() - returns time with maximum accuracy. The time calculation should NOT include the time the random array was created.
The problem itself is that the program takes too long to sort. Yes, this is Bubble sort, but the teacher says that it should work no more than 40 minutes. According to my calculations, my program will give the result only after 5-6 hours. Help identify problems and find a solution, please.
import time
import random
st4rt_time = time.time()
def bubble_sort(list):
swapped = True
while swapped:
swapped = False
for i in range(len(list) - 1):
if list[i] > list[i + 1]:
list[i], list [i + 1] = list [i + 1], list[i]
swapped = True
m = [10, 100, 1000, 10000, 100000]
for e in m:
for i in range(10):
spisok = [random.randint(0, e) for x in range(0, e)]
time_start = time.perf_counter()
bubble_sort(spisok)
time_start += time.perf_counter() // 10
end = time.perf_counter()
spisok = []
print(f'Время выполнения алгоритма списка с {e} элементами: {time.perf_counter() - time_start}, среднее значение времени: {time_start}')
print("------------------------------------------------Время выполнения программы: %s seconds------------------------------------------------" % round(time.time() - st4rt_time))
import time
import random
st4rt_time = time.time()
def bubble_sort(array):
length = len(array)
for i in range(length):
for j in range(0, length - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
mean_time = 0
m = [10, 100, 1000, 10000, 100000]
for e in m:
for i in range(10):
spisok = [random.randint(0, e) for x in range(0, e)]
start_time = time.perf_counter()
bubble_sort(spisok)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
mean_time += elapsed_time
mean_time /= 10
print(f"Время работы списка из {e} элементов:{elapsed_time}. Среднее время работы: {mean_time}")
print("------------------------------------------------Время выполнения программы: %s seconds------------------------------------------------" % round(time.time() - st4rt_time))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question