开始使用免费开始使用

实现快速排序算法

在本练习中,您将实现快速排序算法来对一个数字列表进行排序。

第一步,您将实现 partition() 函数。它在处理列表后返回枢轴的索引,使得枢轴左侧的所有元素都小于枢轴,右侧的所有元素都大于枢轴。

第二步,您将实现 quicksort() 函数,它会调用 partition() 函数。

本练习是课程的一部分

Python 中的数据结构与算法

查看课程

交互式实操练习

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

def partition(my_list, first_index, last_index):
  pivot = my_list[first_index]
  left_pointer = first_index + 1
  right_pointer = last_index
 
  while True:
    # Iterate until the value pointed by left_pointer is greater than pivot or left_pointer is greater than last_index
    while ____ < ____ and ____ < ____:
      left_pointer += 1
    
    while my_list[right_pointer] > pivot and right_pointer >= first_index:
      right_pointer -= 1 
    if left_pointer >= right_pointer:
        break
    # Swap the values for the elements located at the left_pointer and right_pointer
    my_list[left_pointer], my_list[right_pointer] = ____, ____
   
  my_list[first_index], my_list[right_pointer] = my_list[right_pointer], my_list[first_index]
  return right_pointer
编辑并运行代码