快速排序演算法 原理及golang語言實現

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。設要排序的數組是A[0]……A[N-1],首先任意選取一個資料(通常選用數組的第一個數)作為關鍵資料,然後將所有比它小的數都放到它前面,
所有比它大的數都放到它後面,這個過程稱為一趟快速排序。值得注意的是,快速排序不是一種穩定的排序演算法,也就是說,多個相同的值的相對位置也許會在演算法結束時產生變動。

一趟快速排序的演算法是:

1)設定兩個變數i、j,排序開始的時候:i=0,j=N-1;、

2)以第一個數組元素作為關鍵資料,賦值給key,即key=A[0];

3)從j開始向前搜尋,即由後開始向前搜尋(j--),找到第一個小於key的值A[j],將A[j]和A[i]互換;

4)從i開始向後搜尋,即由前開始向後搜尋(i++),找到第一個大於key的A[i],將A[i]和A[j]互換;

5)重複第3、4步,直到i=j; (3,4步中,沒找到合格值,即3中A[j]不小於key,4中A[i]不大於key的時候改變j、i的值,

使得j=j-1,i=i+1,直至找到為止。找到合格值,進行交換的時候i, j指標位置不變。另外,i==j這一過程一定正好是i+或j-完成的時候,此時令迴圈結束)。


go語言實現:
func QSort(values []int) {
fmt.Println("start sort tuple ", values)
if len(values) <= 1 {
fmt.Println("there is only one item in tuple,don't need sort")
return
}
key, head, tail := values[0], 0, len(values)-1
fmt.Println("   --key value is ", key)
for head < tail {
for head < tail && values[tail] >= key {
tail--
}
fmt.Println("   --find the item small than key at position  ", tail, "value is ", values[tail])


for head < tail && values[head] < key {
head++
}
fmt.Println("   --find the item small than key at position  ", head, "value is ", values[head])
values[head], values[tail] = values[tail], values[head]
fmt.Println("   --shift the item at position ", head, "and ", tail)
fmt.Println("   -- now the tuple is ", values)
}
fmt.Println("   --head is  ", head, " and tail is ", tail)
tail++
QSort(values[:tail])
QSort(values[tail:])
}


haskell實現:
qSort :: (Ord a) => [a]->[a]
qSort [] = []
qSort (x:xs) = small_x ++ [x] ++ bigger_x
           where small_x = qSort [ a | a <- xs, a < x]
                 bigger_x = qSort [a | a <- xs, a >= x]


可見, 命令式語言是嘗試解決問題。 函數式語言是定義問題的解。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.