Python:實現circle sort圓形排序算法
def circle_sort(collection: list) -> list:
if len(collection) < 2:
return collection
def circle_sort_util(collection: list, low: int, high: int) -> bool:
swapped = False
if low == high:
return swapped
left = low
right = high
while left < right:
if collection[left] > collection[right]:
collection[left], collection[right] = (
collection[right],
collection[left],
)
swapped = True
left += 1
right -= 1
if left == right:
if collection[left] > collection[right + 1]:
collection[left], collection[right + 1] = (
collection[right + 1],
collection[left],
)
swapped = True
mid = low + int((high - low) / 2)
left_swap = circle_sort_util(collection, low, mid)
right_swap = circle_sort_util(collection, mid + 1, high)
return swapped or left_swap or right_swap
is_not_sorted = True
while is_not_sorted is True:
is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(circle_sort(unsorted))