gpt4 book ai didi

python - 假定一个值作为初始值,在循环中更新它的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:11 25 4
gpt4 key购买 nike

我正在学习选择排序算法

from typing import List
def find_smallest(arr:List) -> int:
smallest = arr[0] #set pivot
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index

def selection_sort(arr) -> List:
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr

我对函数find_smallest很好奇,
它首先假定 arr[0] 为最小值并启动循环。

我知道完整的代码叫做选择排序算法,

在循环中假设和更新它的值怎么样,有没有术语?

最佳答案

我认为 冒泡排序 就是答案。在我看到你的问题之前,我从未将 bubble loop 视为最小的假设:D

def sort(arr):
for i in range(len(arr)):
# we presume a[i] is the smallest one. Then we update by compare it with the rest of the list
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]: # if our assumption is wrong (arr[i] is not the smallest), update it with arr[j] (which is smaller than arr[i])
swap(arr[i], arr[j])

# After this `for j` loop, arr[i] will be the smallest value of the list

关于python - 假定一个值作为初始值,在循环中更新它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53425193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com