本次对于1000行数据用6种排序方法进行排序
6种排序算法如下:
- 插入排序(insertion sort)
- 冒泡排序(bubble sort)
- 归并排序(merge sort)
- Tim排序(Tim’s sort)
- 快速排序(quick sort)
- 计数排序(counting sort)
数据生成源码:
import random
file = open("test_data.txt", "w")
for j in range(2, 1002):
array = [random.randint(1, 1000) for i in range(1, j)]
random.shuffle(array)
string = str(array[0])
for index in range(1, j - 1):
string += " "
string += str(array[index])
string += "\n"
file.write(string)
file.close()
部分测试数据截图:
插入排序(insertion sort)代码
import time
time_file = open("insertion_time.txt", "w")
number_file = open("test_data.txt", "r")
def teacher_insertion_sort(arr):
start_time = time.process_time_ns()
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[i]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
end_time = time.process_time_ns()
return end_time - start_time
while True:
test_array = (number_file.readline())[:-1].split(" ")
if test_array != [""]:
time_file.write(str(teacher_insertion_sort(test_array)))
time_file.write("\n")
else:
break
冒泡排序(bubble sort)代码
import time
def bubble_sort(arr):
start_time = time.process_time_ns()
n = len(arr)
swapped = False
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if not swapped:
end_time = time.process_time_ns()
return end_time - start_time
end_time = time.process_time_ns()
return end_time - start_time
time_file = open("bubble_time.txt", "w")
number_file = open("test_data.txt", "r")
while True:
test_array = (number_file.readline())[