python - 使用排序和大小命令编辑代码以在 excel 电子表格中获得所需的大小
问题描述
使用python:修改“Sort Timer”程序收集数据完成电子表格。将程序中的“大小”变量调整为电子表格中指示的大小。根据需要将程序中的选择排序方法替换为其他排序方法的代码。将所有时间四舍五入到最接近的秒数:
import random
import time
import sys
sys.setrecursionlimit(2000)
def main():
size = 300000
list = []
for i in range(size):
list.append(random.randint(0, 100000 - 1))
print("Starting Sort ...")
startTime = time.time()
quickSort(list)
endTime = time.time()
print("Exection time for Selection Sort with", size, "values is: ",
endTime - startTime)
# The function for sorting the numbers
def quickSort(list):
quickSortHelper(list, 0, len(list) - 1)
def quickSortHelper(list, first, last):
if last > first:
pivotIndex = partition(list, first, last)
quickSortHelper(list, first, pivotIndex - 1)
quickSortHelper(list, pivotIndex + 1, last)
# Partition list[first..last]
def partition(list, first, last):
pivot = list[first] # Choose the first element as the pivot
low = first + 1 # Index for forward search
high = last # Index for backward search
while high > low:
# Search forward from left
while low <= high and list[low] <= pivot:
low += 1
# Search backward from right
while low <= high and list[high] > pivot:
high -= 1
# Swap two elements in the list
if high > low:
list[high], list[low] = list[low], list[high]
while high > first and list[high] >= pivot:
high -= 1
# Swap pivot with list[high]
if pivot > list[high]:
list[first] = list[high]
list[high] = pivot
return high
else:
return first
main()
名为 Sort Compare.xlsx 的 Excel 电子表格如下所示: