排序算法 之 快速排序 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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章