การนำอัลกอริทึม Quicksort ไปใช้งาน
ในแบบฝึกหัดนี้ คุณจะนำอัลกอริทึม Quicksort ไปใช้เพื่อเรียงลำดับรายการตัวเลข
ในขั้นตอนแรก จะได้นำฟังก์ชัน partition() ไปใช้งาน ซึ่งฟังก์ชันนี้จะคืนค่าดัชนีของ pivot หลังจากประมวลผลรายการตัวเลขแล้ว โดยองค์ประกอบทางซ้ายของ pivot จะมีค่าน้อยกว่า pivot และองค์ประกอบทางขวาจะมีค่ามากกว่า pivot
ในขั้นตอนที่สอง จะได้นำฟังก์ชัน 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