開始使用免費開始

實作 quicksort 演算法

在這個練習中,你將實作 quicksort 演算法來排序一串數字。

第一步,你會實作 partition() 函式。它會在處理這串數字後,回傳樞紐(pivot)的索引,使得樞紐左側的所有元素都小於樞紐,樞紐右側的所有元素都大於樞紐。

第二步,你會實作 quicksort() 函式,並在其中呼叫 partition()

本練習屬於課程

Data Structures and Algorithms in 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
編輯並執行程式碼