快速排序c++和python對比分析

來源:互聯網
上載者:User

標籤:python   快速排序   c++   遍曆   遞迴   


C++的快速排序基本思想就是,任意取出一位作為對比位x,分別從序列兩端開始探測,先從右邊到左找到一個比x大的數,在從左邊到右找到一個比x小的數,然後交換他們,一直迴圈到i=j。這一次交換完畢之後,將x換到中間位置,因為左邊都比它小,右邊都比它大,所以它在中間。在函數最後,有一個遞迴函式,分別在對左邊和右邊進行剛才的排序,直到將元素分解到1個的時候停止,迴圈結束。

void quicksort(int left,int right){int i,j,t,temp;if(left>right)return;temp = a[left];i = left;j = right;while(i!=j){while(a[j]>=temp && i<j)j--;while(a[i]<=temp && i<j)i++;if(i<j){t = a[i];a[i] = a[j];a[j] = t;}}a[left] = a[i];a[i] = temp;quicksort(left,i-1);quicksort(i+1,right);}

python中的快速排序實現思想類似,但是代碼會簡單一點,開始的時候建立兩個列表元素,從隊列中取出一個元素x,將整個隊列迴圈遍曆一遍,將小於取出x的元素放在less中,將大於x的元素放在greater裡。最後返回一個遞迴的運算式。

def quicksort(array):less = []greater = []if len(array) <= 1:return arraypivot = array.pop()for x in array:if x <= pivot: less.append(x)else: greater.append(x)return quicksort(less) + [pivot] + quicksort(greater)


快速排序c++和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.