for
# 冒泡排序
# arr = [64, 34, 25, 12, 22, 11, 90]
arr = [-64, 34, 25, 12, 22, 11, 90]
print(arr)
# 遍历所有数组元素
for i in range(1,len(arr)):
for j in range(0, len(arr) - i):
if arr[j] < arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
else:
print(arr)
输出结果如下:
while
arr = [-64, 34, 25, 12, 22, 11, 90]
print(arr)
i = 1
while i < len(arr):
j = 0
while j < len(arr)-i:
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
else:
j += 1
i += 1
else:
print(arr)
输出结果如下: