排序算法 之 快速排序 QuickSort

介紹

快速排序通常明顯比同爲 O(nlogn) 的其他算法更快,因此常被採用,而且快排採用了分治法的思想,所以在很多筆試面試中能經常看到快排的影子。可見掌握快排的重要性。

步驟

  • 從數列中挑出一個元素作爲基準數。
  • 分區過程,將比基準數大的放到右邊,小於或等於它的數都放到左邊。
  • 再對左右區間遞歸執行第二步,直至各區間只有一個數。

這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

代碼

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 16:10:13 2016

@author: zang
"""
from matplotlib import pyplot as plt
import random

def quickSort(unsortedList):
    if len(unsortedList)<2:
        return unsortedList
    less=[]
    greater=[]
    middle=unsortedList.pop(0)
    for item in unsortedList:
        if item < middle:
            less.append(item)
        else:
            greater.append(item)
    return quickSort(less)+[middle]+quickSort(greater)

def plotScatter(inputList):
    plt.scatter(range(len(inputList)),inputList)
    plt.show()

if __name__ == "__main__":
    num_list = range(1000)
    unsortedList = random.sample(num_list, 30)
    print "unsortedList:"
    plotScatter(unsortedList)
    print unsortedList
    sortedList = quickSort(unsortedList)
    print "sortedList:"
    plotScatter(sortedList)
    print sortedList

測試

輸入

[918, 965, 651, 275, 993, 729, 952, 764, 947, 840, 916, 299, 213, 384, 263, 606, 641, 17, 185, 939, 118, 610, 382, 816, 344, 60, 236, 26, 775, 399]

這裏寫圖片描述

輸出

[17, 26, 60, 118, 185, 213, 236, 263, 275, 299, 344, 382, 384, 399, 606, 610, 641, 651, 729, 764, 775, 816, 840, 916, 918, 939, 947, 952, 965, 993]

這裏寫圖片描述

分析

情況 性能
Worst case performance: O(n2)
Best case performance: O(nlogn)
Average case performance: O(nlogn)
Worst case space complexity: O(logn)
發佈了126 篇原創文章 · 獲贊 94 · 訪問量 46萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章