输入三个整数x, y, z,形成一个列表,请把这n个数由小到大输出
这就是要求升序排列,用之前写过几种方法
法一
#数组
li=[1,3,5,7,2,0]
# 用sort()排序
li_sort = sorted(li, reverse = False)
print('用sort方法,排列结果:{}'.format(li_sort))
法二:冒泡排序
# 冒泡排序
def bubbleSort(m):
m = m.copy()
for time in range(1, len(m)):
for index in range(len(m) - time):
if m[index] > m[index+1]:
m[index], m[index+1] = m[index+1] , m[index]
return m
print(bubbleSort(li))
法三:选择排序
# 选择排序
def selectSort(m):
m = m.copy()
for seat_L in range(len(m)-1):
for seat_R in range(seat_L+1, len(m)):
if m[seat_L] > m[seat_R]:
m[seat_L], m[seat_R] = m[seat_R], m[seat_L]
return m
print(selectSort(li))
法三:插入排序
def insertSort(m):
m = m.copy()
result = m[:1]
for index_choose in range(1, len(m)):
for index_insert in range(len(result) + 1):
print(result, index_insert,'\n',m, index_choose,'\n\n')
if index_insert != index_choose and m[index_choose] < result[index_insert]:
result.insert(index_insert, m[index_choose])
break
if index_insert == index_choose:
result.append(m[index_choose])
return result
print(insertSort(li))
法四:希尔排序
import math
def shellSort(arr):
gap=1
while(gap < len(arr)/3):
gap = gap*3+1
while gap > 0:
for i in range(gap,len(arr)):
temp = arr[i]
j = i-gap
while j >=0 and arr[j] > temp:
arr[j+gap]=arr[j]
j-=gap
arr[j+gap] = temp
gap = math.floor(gap/3)
return arr