幾種常用演算法的Python實現

來源:互聯網
上載者:User

標籤:

     呵呵!今天興緻高,用python重寫了部分排序演算法,也為筆試做下準備,繼續加油

// 冒泡排序

def bubble(x,n):
    ‘‘‘This function orders the original items x

    x is list,n is the length of x‘‘‘
    for i in range(n):
        for j in range(n-1):
            if x[j] >x[j+1]:
                t = x[j]
                x[j]= x[j+1]
                x[j+1] = t

// 插入排序
def insert(x,n):
     i = 1
     while i<n-1:
         key = x[i]
         j = i-1
         while j>=0 and key<x[j]:
             x[j+1]= x[j]
             j -= 1
         x[j+1] = key
         i += 1

// 選擇排序
def select(x,n):
    for i in range(n-1):
        key = i
        for j in range(i+1,n):
            if x[j] < x[key]:
                 key = j
        if key!=i:
            t = x[i]
            x[i] = x[key]
            x[key] = t

// 快速排序
def partition(x,low,high):
    key = x[low]
    while low<high:
        while low<high and x[high]>=key:
            high -= 1
        if low < high:
            x[low]= x[high]
            low += 1
        while low <high and x[low]<=key:
            low += 1
        if low < high:
            x[high] = x[low]
            high -= 1
    x[low] = key
    return low
def quick(x,low,high):
    if low < high:
       p = partition(x,low,high)
       quick(x,low,p-1)
       quick(x,p+1,high)

幾種常用演算法的Python實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.