python - 这段代码是如何工作的?选择排序 Python
问题描述
嗨,我不明白这段代码是如何工作的。请解释一下。谢谢你。
#how this function finds the smallest element of the array.
def findSmallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest: #--> why this is here and what does it mean?
smallest_index = i
smallest = arr[i]
return smallest_index
def selectionSort(arr):
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selectionSort([5, 3, 6, 2, 10]))
“findSmallest”函数如何找到数组的最小元素?
解决方案
您特别质疑的那一行是比较值。如果当前索引处的值(由 for 循环计算)小于 minimum 中存储的值(最初是列表中的第一个值),则将该值存储为新的最小值。我在代码中添加了更多注释来解释其余部分。
#how this function finds the smallest element of the array.
def findSmallest(arr): #function with a parameter to hold an array
smallest = arr[0] #index 0 of passed array
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest: #if the value in the array at the index of i is smaller than the value at the index of 0
smallest_index = i #the index of the smallest number is now at the position of i
smallest = arr[i] #the smallest number is now the number at the index of i
return smallest_index #return the index position of the smallest number
def selectionSort(arr): #function passed an array
newArr = []
for i in range(len(arr)): #loop through passed array
smallest = findSmallest(arr) #call the findSmallest function
newArr.append(arr.pop(smallest)) #remove the smallest number from the passed array and add it to the new one. Repeat until passed array is empty
return newArr #return the new array
print(selectionSort([5, 3, 6, 2, 10]))
推荐阅读
- scala - Maven Gatling 3.0.2 - NoSuchMethodError
- python - Tensorflow:索引中的“交错”序列掩码?
- linux - 使用 centos 7 作为操作系统对安装在谷歌云实例上的 tableau 服务器进行 Web 访问
- splunk - Splunk 只选择匹配的 JSON 数据
- windows - 使用 Powershell 自动禁用 Windows 更新
- javascript - 使用“index.js”导入 ES6 JS 模块的问题
- java - 如何安装 JDK 和 JRE
- json - 在 Google 表格中解析 JSON
- for-loop - Jekyll 中的嵌套液体循环不会正确地迭代多个子项
- javascript - 如何在 html 文件上显示 ejs 数据?