Как работает этот код? Сортировка выбора Python - PullRequest
0 голосов
/ 27 мая 2020

привет, я не понимаю, как работает этот код. Объясните, пожалуйста. Спасибо.

#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 находит наименьший элемент массива?

Ответы [ 2 ]

2 голосов
/ 27 мая 2020

Строка, которую вы конкретно задали, сравнивает значения. Если значение в текущем индексе (вычисленном с помощью for-l oop) меньше значения, хранящегося в наименьшем (изначально первое значение в списке), сохраните это значение как новое наименьшее значение. Я добавил дополнительные комментарии к коду, чтобы объяснить остальное.

#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]))
1 голос
/ 27 мая 2020

Читая это, похоже, что он упорядочивает заданные элементы и помещает их в массив от наименьшего к наибольшему в зависимости от значения. Чтобы ответить на ваш вопрос о line 5, он сравнивает сохраненное целочисленное значение i с другими в selectionSort, чтобы следующий код мог распечатать отсортированный массив. def selectionSort(arr) имеет переменную smallest, которая использует findSmallest для добавления списка элементов в числовом порядке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...