Python快速排序演算法執行個體分析,python演算法執行個體分析

來源:互聯網
上載者:User

Python快速排序演算法執行個體分析,python演算法執行個體分析

本文執行個體講述了Python快速排序演算法。分享給大家供大家參考,具體如下:

快速排序的時間複雜度是O(NlogN)

演算法描述:

① 先從序列中取出一個數作為基準數
② 分區過程, 將比這個數大的數全部放到它的右邊, 小於或等於它的數全部放到它的左邊
③ 再對左右區間重複第二步, 直到各區間只有一個數

假設對 6, 1, 2, 7, 9, 3, 4, 5, 10, 8 進行排序, 首先在這個序列中隨便找一個基準數(用來參照), 比如選擇 6 為基準數, 接下來把所有比基準數大的數放在6的右邊, 比6小的數放在左邊

原理分析:

① 選擇最左邊的數為基準數key
② 設立兩個遊標 low 和 high , 分別指向數組的最低位和最高位
③ 然後high先動, 如果high位上的數比key大, 則向前走, 如果high-1位上的數比key大, 繼續向前走, 直到該位上的數<=key
④ 此時比較low位, 如果<=key, low向後走, 變為low+1, 依次類推, 直到該位上的數比key大
⑤ 交換high和low位上的數
⑥ 重複以上步驟, 直到low=high , 交換 key 和 high 位上的值
⑦ 最後進行遞迴操作

範例程式碼:

#!/usr/bin/env python# coding:utf-8# 設定最低位和最高位def quickSort(nums, low, high):  # 設定一個比較基準key  key = nums[low]  while low<high:    # 如果最高位的數 大於等於 key則向前走    while low<high and nums[high] >= key:      high -= 1    # 如果最低位的數 小於等於 key則向後走    while low<high and nums[low] <= key:      low += 1    # 交換值    nums[low], nums[high] = nums[high], nums[low]  #最後low=high, 此時交換key和high位上的值, 使小於key的值在key左邊, 大的在key右邊  nums[nums.index(key)], nums[low] = nums[low], nums[nums.index(key)]  # 返回最低位的位置  return low# 進行重複操作def interval(nums, low, high):  if low<high:    # 進行排序並得到最低位位置以迴圈操作    key_index = quickSort(nums, low, high)    interval(nums, low, key_index)    interval(nums, key_index+1, high)nums = [64,3,9,2,4,7,0,12,45,]interval(nums, 0, len(nums)-1)print "幫客之家測試結果:"print nums"""[0, 2, 3, 4, 7, 9, 12, 45, 64]"""

運行結果:

PS:關於排序演算法的詳細說明還可參考本站線上工具:

線上動畫示範插入/選擇/冒泡/歸併/希爾/快速排序演算法過程工具
http://tools.jb51.net/aideddesign/paixu_ys

聯繫我們

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