開始使用免費開始

比較線上購物體驗

現在就體驗演算法效率的威力!執行提供的程式碼,並比較四種不同演算法的效能(氣泡排序與線性搜尋,以及快速排序與二元搜尋)。

不需要寫程式。只要調整一個參數,看看在不同條件下它們的表現如何。請變更頂端名為 num_items 的參數。(此參數模擬線上購物目錄中有多少項商品)。

執行程式碼並比較結果,注意當我們把數量從 1000 增加到 10000,兩個選項之間所需時間會差多少。

想像一下:如果你要在電商網站上依價格排序商品,這兩組演算法相比,其中一組會讓體驗好上許多(也就是更快)。

本練習屬於課程

電腦科學的核心概念

檢視課程

練習說明

  • num_items 改成任何你想比較的數字。(例如:想像 www.amazon.com 有 1,000 件商品,就把 num_items = 1000)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Change this parameter
num_items = 1000

####### Leave the code below this line alone ########
catalog = [random.randint(0, num_items) for _ in range(num_items)]
total_time_bubble_linear = time_bubble_sort_and_linear_search(catalog)
catalog = [random.randint(0, num_items) for _ in range(num_items)]
total_time_quick_binary = time_quick_sort_and_binary_search(catalog)

df = pd.DataFrame({"Method": ["Bubble Sort + Linear Search", "Quick Sort + Binary Search"],
                   "Total Time (seconds)": [total_time_bubble_linear, total_time_quick_binary]})
print(df)
編輯並執行程式碼