1. 程式人生 > >python-快速排序

python-快速排序

# -*- coding: utf-8 -*-
import sys
def quikeSort(m,R,a):#從m到R(這裡設定為最後位置),以R作為參考,分成小中大三區
    L = m
    more = R
    less = L-1
    while L<more:
        if a[L]<a[R]:#最後一個作為參考值
            less +=1
            a[less],a[L]=a[L],a[less]####交換方法
            # temp = a[less]
            # a[less]=a[L]
            # a[L]=temp
            L += 1
        elif a[L]>a[R]:
            more -=1
            tem = a[more]
            a[more]=a[L]
            a[L]=tem
        else:
            L +=1
    te = a[more]
    a[more] = a[R]
    a[R] = te
    # sys.setrecursionlimit(10000000)#手動設定遞迴呼叫深度,最好是優化自己的程式碼
    # quikeSort(m, less+1, a)
    # quikeSort(more, R, a)
    return a#等於區的位置

if __name__=="__main__":
    a= [1,5,2,3,6,4,8,9,7,8,5,25,2,7,6]
    print("原列表為:%s" %a)
    quikeSort(3,14,a)
    print("新列表為:%s" %a)
#     # print a
#     del a[2]#刪除元素
#     b = a
#     print ("b為:      %s" %b)
# ######################################交換
#     a=[1, 5, 3, 4, 2, 5, 6, 6, 7, 25, 9, 7, 8, 8, 5,8]
#     b=[1, 5, 2, 3, 6, 4, 8, 9, 7, 8, 5, 25, 2, 7, 6]
#     a,b=b,a
#     print a
#     print b
#     a[0], a[1] = a[1], a[0]
#     print a
#     print a[0],a[1]
# ##################################################