python快速排序代码实例

yipeiwu_com6年前Python基础

一、 算法描述:

1.先从数列中取出一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。

 二、python快速排序代码

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def sub_sort(array,low,high):
    key = array[low]
    while low < high:
        while low < high and array[high] >= key:
            high -= 1
        while low < high and array[high] < key:
            array[low] = array[high]
            low += 1
            array[high] = array[low]
    array[low] = key
    return low


def quick_sort(array,low,high):
     if low < high:
        key_index = sub_sort(array,low,high)
        quick_sort(array,low,key_index)
        quick_sort(array,key_index+1,high)


if __name__ == '__main__':
    array = [8,10,9,6,4,16,5,13,26,18,2,45,34,23,1,7,3]
    print array
    quick_sort(array,0,len(array)-1)
    print array

结果:
[8, 10, 9, 6, 4, 16, 5, 13, 26, 18, 2, 45, 34, 23, 1, 7, 3]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 16, 18, 23, 26, 34, 45]

相关文章

python定时检查某个进程是否已经关闭的方法

本文实例讲述了python定时检查某个进程是否已经关闭的方法。分享给大家供大家参考。具体如下: import threading import time import os impo...

python中私有函数调用方法解密

本文实例讲述了python中私有函数调用方法。分享给大家供大家参考,具体如下: 与大多数语言一样,Python 也有私有的概念: ① 私有函数不可以从它们的模块外面被调用 ② 私有类方法...

Python 获取项目根路径的代码

在 运行,调试,打包成exe 三个不同场景下获取跟路径,用于解决获取资源文件绝对路径问题。 工具类代码如下: import sys import os class pathutil(...

Python collections模块使用方法详解

Python collections模块使用方法详解

一、collections模块 1.函数namedtuple (1)作用:tuple类型,是一个可命名的tuple (2)格式:collections(列表名称,列表) (3)̴...

python2.6.6如何升级到python2.7.14

python2.6.6如何升级到python2.7.14

其实网上有很多关于python2.6.6 升级到python2.7的文章,但是我对比这些类似的文章升级之后,发现其中有错误的地方,于是决定还是自己写一个真正的升级过程。 我的虚拟机里安装...