首页 > 解决方案 > 这段代码是如何工作的?选择排序 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”函数如何找到数组的最小元素?

标签: pythonsorting

解决方案


您特别质疑的那一行是比较值。如果当前索引处的值(由 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]))

推荐阅读