开始使用免费开始使用

编写 Selection Sort

在上一段视频中,您学习了 selection sort 算法。

在本练习中,您需要通过补全 selection_sort() 函数来实现该算法。

本练习是课程的一部分

Python 中的数据结构与算法

查看课程

练习说明

  • lowest 设为列表中索引为 i 的元素。
  • 从变量 i 的下一个位置开始,再次遍历列表。
  • 比较索引为 j 的列表元素是否小于 lowest

交互式实操练习

通过完成这段示例代码来试试这个练习。

def selection_sort(my_list):
  list_length = len(my_list)
  for i in range(list_length - 1):
    # Set lowest to the element of the list located at index i
    lowest = ____
    index = i
    # Iterate again over the list starting on the next position of the i variable
    ____ j in range(____, list_length):
      # Compare whether the element of the list located at index j is smaller than lowest
      if _____:
        index = j
        lowest = my_list[j]
    my_list[i] , my_list[index] = my_list[index] , my_list[i]
  return my_list

my_list = [6, 2, 9, 7, 4, 8] 
selection_sort(my_list)
print(my_list)
编辑并运行代码