計數排序演算法

來源:互聯網
上載者:User

標籤:排序演算法   c++   

基本思想

統計數組data,小於data[i]的個數為N,則把data[i]放在第N+1個位置上面。

實用範圍:

所有數都在[0,max]範圍內,max為數組的最大值,適用於max不是很大的情況。

對於資料2 5 3 0 2 3 0 3程式執行的過程如所示:





C++代碼:


#include <iostream>using namespace std;namespace mysort{//找出數組中的最大值int Max(int * data, int len){int ret = -1;for (int i = 0; i < len; i++)if (data[i]>ret)ret = data[i];return ret;}void sort(int *data, int len){int max = Max(data, len);int *c = new int[max+1];int *ret = new int[len];memset((void*)c, 0, sizeof(int)* (max + 1));for (int i = 0; i < len; ++i) c[data[i]]++;//統計每個數出現的次數for (int i = 0; i < max; i++) c[i + 1] += c[i];//統計小於某個數出現的次數for (int i = len - 1; i >= 0; i--){ret[ c[ data[i] ] - 1 ] = data[i];--c[data[i]];}memcpy((void*)data, (void*)ret, sizeof(int)*len);}};int main(){//計數排序的前提是,所有數都在[0,max]範圍內,適用於數組最大值不是很大的情況。int a[] = { 0, 4, 3, 1, 2, 3, 4, 5, 6, 4, 3, 2 };mysort::sort(a, 12);return 0;}

總結:計數排序和通常的交換排不同,它直接將待排序的數放在了排序後正確的位置。演算法雖然有O(N)的時間和空間複雜度,但它的使用範圍有一定的局限性。演算法思路和用位向量排序(《編程珠璣》第一章)有相似之處。

Key Word:不同問題,不同的分析。




聯繫我們

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