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]

相关文章

python3.x 生成3维随机数组实例

python3.x 生成3维随机数组实例

如下所示: import numpy as np a=np.random.randint(0,10,size=[3,3,3]) print(a) 以上这篇python...

Python通过VGG16模型实现图像风格转换操作详解

Python通过VGG16模型实现图像风格转换操作详解

本文实例讲述了Python通过VGG16模型实现图像风格转换操作。分享给大家供大家参考,具体如下: 1、图像的风格转化 卷积网络每一层的激活值可以看作一个分类器,多个分类器组成了图像在这...

python逐行读写txt文件的实例讲解

实例如下所示: # -*-coding:utf-8-*- import os file_obj = open("test2.txt") all_lines = file_obj.re...

Python中时间datetime的处理与转换用法总结

python中日期类datetime功能比较强大,使用起来很方便,把常用的两种用法总结如下: from datetime import datetime from datetime...

详解python 利用echarts画地图(热力图)(世界地图,省市地图,区县地图)

详解python 利用echarts画地图(热力图)(世界地图,省市地图,区县地图)

首先安装对应的python模块 $ pip install pyecharts==0.5.10 $ pip install echarts-countries-pypkg $ pip...