整体需求完善

This commit is contained in:
2025-07-30 12:15:30 +08:00
parent c254e2f94c
commit 28ef203b90
4 changed files with 175 additions and 27 deletions

View File

@ -0,0 +1,57 @@
import random
import sys
def quick_sort(arr):
"""
快速排序主函数,支持空数组处理
"""
if len(arr) <= 1:
return arr
def partition(low, high):
pivot_index = random.randint(low, high) # 随机选择基准
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
def recur_sort(low, high):
if low < high:
pi = partition(low, high)
recur_sort(low, pi - 1)
recur_sort(pi + 1, high)
recur_sort(0, len(arr) - 1)
return arr
if __name__ == "__main__":
# 从命令行参数读取数据
if len(sys.argv) > 1:
try:
# 处理多种输入格式:逗号分隔、空格分隔或混合分隔
input_str = " ".join(sys.argv[1:])
input_data = [float(x) if '.' in x else int(x)
for x in input_str.replace(',', ' ').split()]
print("原始输入:", sys.argv[1:])
print("解析数据:", input_data)
sorted_arr = quick_sort(input_data.copy())
print("排序结果:", sorted_arr)
except ValueError:
print("错误:输入数据包含非数字字符,请确保只输入数字")
print("用法: python script.py [数字1 数字2 ...]")
print("示例: python script.py 3 0 8 7 2 1 9 4")
else:
print("未提供输入数据,使用默认测试用例")
test_case = [3, 0, 8, 7, 2, 1, 9, 4]
print("测试数据:", test_case)
print("排序结果:", quick_sort(test_case.copy()))

View File

@ -0,0 +1,57 @@
import random
import sys
def quick_sort(arr):
"""
快速排序主函数,支持空数组处理
"""
if len(arr) <= 1:
return arr
def partition(low, high):
pivot_index = random.randint(low, high) # 随机选择基准
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
def recur_sort(low, high):
if low < high:
pi = partition(low, high)
recur_sort(low, pi - 1)
recur_sort(pi + 1, high)
recur_sort(0, len(arr) - 1)
return arr
if __name__ == "__main__":
# 从命令行参数读取数据
if len(sys.argv) > 1:
try:
# 处理多种输入格式:逗号分隔、空格分隔或混合分隔
input_str = " ".join(sys.argv[1:])
input_data = [float(x) if '.' in x else int(x)
for x in input_str.replace(',', ' ').split()]
print("原始输入:", sys.argv[1:])
print("解析数据:", input_data)
sorted_arr = quick_sort(input_data.copy())
print("排序结果:", sorted_arr)
except ValueError:
print("错误:输入数据包含非数字字符,请确保只输入数字")
print("用法: python script.py [数字1 数字2 ...]")
print("示例: python script.py 3 0 8 7 2 1 9 4")
else:
print("未提供输入数据,使用默认测试用例")
test_case = [3, 0, 8, 7, 2, 1, 9, 4]
print("测试数据:", test_case)
print("排序结果:", quick_sort(test_case.copy()))