python实现快速排序算法
2015-07-23 20:01
746 查看
python 实现快速排序算法
介绍:
快速排序通常明显比同为Ο(n log n)的其他算法更快,因此常被采用,而且快排采用了分治法的思想,所以在很多笔试面试中能经常看到快排的影子。可见掌握快排的重要性。
步骤:
从数列中挑出一个元素作为基准数。
分区过程,将比基准数大的放到右边,小于或等于它的数都放到左边。
再对左右区间递归(执行前两步),直至各区间只有一个数。
# -*- coding: UTF-8 -*-
''' this script is the implementation of quick sort algorithm
Pycharm, python 2.7.9
by will
time: 2015.07.23
'''
import random
def quick_sort(L):
if len(L)<2: return L
pivot_element = random.choice(L)
small = [i for i in L if i < pivot_element]
medium = [i for i in L if i == pivot_element]
large = [i for i in L if i > pivot_element]
# return quick_sort(small) + [pivot_element] + quick_sort(large) # no duplicate
return quick_sort(small) + medium +quick_sort(large) # the original list with duplicate
# example
m = [4,2,6,7,0,2,3,9]
print quick_sort(m)
参考:
【1】/article/1383496.html
【2】http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
相关文章推荐
- Python多进程时可以用进程池
- [笔记]python multiprocessing模块
- Python爬虫抓取csdn博客
- python 多进程
- getopt在Python中的使用(转)
- python cookielib 登录人人网
- Python的捕虫笔记
- Python的捕虫笔记
- 那些年,我们读过的python!
- Python中的文本处理
- python连接mysql
- 快速启动cmd下的Python---如何使用java运行多条cmd命令
- Python 推断素数
- python基础教程总结11——图形用户界面GUI
- 如何捅破python编程的那层纸之三
- 飞跃式发展的后现代 Python 世界
- python开发_xml.etree.ElementTree_XML文件操作_该模块在操作XML数据是存在安全隐患_慎用
- 提取网址的python练习
- Python开发MySQL数据库(表)克隆工具
- 初识python django, 让我们一起进入python的世界吧