zoukankan      html  css  js  c++  java
  • python实现快速排序

    2.快速排序

    • 设定一个基数,原始列表中第0个列表元素的数值,基数需要存储在一个mid的变量中。
    • 设定两个变量一个为low(对应表第一个数据的下标),一个为high(对应列表最后下标)
    • 从右开始偏移high,需要将high指向数值跟基数进行大小比较,如果high指向的数值>基数,则让high向左偏移一位,继续进行比较,直到high指向的数值小于了基数。
    • 快排特点:选择一个mid,将比mid小的数据放在mid左侧,比mid大的数据放在mid右侧。
    def sort(alist,start,end):
        low = start
        high = end
        
        if low > high:
            return
        
        mid = alist[low]
        while low < high:
            while low < high:
                if alist[high] > mid:#将high向左偏移
                    high -= 1
                else:
                    alist[low] = alist[high]
                    break
    
            while low < high:
                if alist[low] < mid:#向右移动low
                    low += 1
                else:
                    alist[high] = alist[low]
                    break
                
        if low == high:
            alist[low] = mid#alist[high] = mid
            
        #将sort的操作作用到基数左侧部分
        sort(alist,start,low-1)
        #将sort的操作作用的基数右侧部分
        sort(alist,high+1,end)
        
        return alist
    alist = [6 ,1, 2, 7, 9, 3, 4, 5, 10, 8]
    alist = sort(alist,0,len(alist)-1)
    print(alist)
    #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
  • 相关阅读:
    Recommender Systems 基于知识的推荐
    粒子群优化算法简介
    彻底弄懂LSH之simHash算法
    c++ 字符串函数用法举例
    Linux上的运行的jar包
    推荐系统判定标准
    python 细枝末节
    PV UV
    python解析json
    生成n对括号的所有合法排列
  • 原文地址:https://www.cnblogs.com/xujunkai/p/12341217.html
Copyright © 2011-2022 走看看