Project

General

Profile

Files » maopaolist.py

UserName LastName, 01/15/2025 03:45 PM

 
def bubble_sort(nums, ascending=True):
n = len(nums)
total_swaps = 0

for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if (ascending and nums[j] > nums[j + 1]) or (not ascending and nums[j] < nums[j + 1]):
nums[j], nums[j + 1] = nums[j + 1], nums[j]
total_swaps += 1
swapped = True


print(f"第 {i + 1} 轮比较后: {nums}")

if not swapped:
break

return total_swaps


def main():

user_input = input("请输入多个整数,用空格分隔: ")
nums = list(map(int, user_input.split()))

order = input("请输入排序方式(升序输入 'asc',降序输入 'desc'): ")
ascending = order.strip().lower() == 'asc'

total_swaps = bubble_sort(nums, ascending)

print("排序后的结果:", nums)
print("总的交换次数:", total_swaps)

if __name__ == "__main__":
main()
(72-72/437)