Python有内置的max函数可以取最大值:
max([2,3,9,1,0])
也可以使用sorted先排序,再索引取出最大值:
sorted([2,3,9,1,0])[-1]
如果不用内置函数,自己排序算法来找出最大值,也有很多选择。
比如冒泡排序、循环排序、交换排序、插入排序、选择排序等等。
1、冒泡排序
是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。
def bubble_sort(arr, simulation=False):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
x = -1
while swapped:
swapped = False
x = x + 1
for i in range(1, n-x):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
print(bubble_sort([2,4,5,1]))
2.循环排序
def cycle_sort(arr):
len_arr = len(arr)
for cur in range(len_arr - 1):
item = arr[cur]
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
if index == cur:
continue
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
while index != cur:
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
return arr
print(cycle_sort([2,4,5,1]))
3、交换排序
def exchange_sort(arr):
arr_len = len(arr)
for i in range(arr_len-1):
for j in range(i+1, arr_len):
if(arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
return arr
print(exchange_sort([2,4,5,1]))
4、插入排序
def insertion_sort(arr, simulation=False):
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cursor:
# Swap the number down the list
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = cursor
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
print(insertion_sort([2,4,5,1]))
5、选择排序
def selection_sort(arr, simulation=False):
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
# "Select" the correct value
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
print(selection_sort([2,4,5,1]))
通过排序算法得到顺序列表后,通过索引就可以得到最大值,so easy!