《演算法導論》CLRS演算法C++實現(五)P98 計數排序

來源:互聯網
上載者:User

第八章 線性時間排序

8.2 計數排序

這個演算法比較簡單。計數排序的基本思想就是對每一個輸入元素x,確定出小於x的元素個數。然後就可以把x直接放到它的最終輸出數組的位置上。例如如果有17個元素小於x,則x旅遊屬於第18個輸出位置。

假定輸入的日企 數組A[1..n],length[A]=n。另外還需要兩個數組:存放排序結果的B[1..n],以及提供臨時儲存區的C[0..k]。

COUNTING-SORT(A, B, k)

1 for i ← 0 to k2     do C[i] ← 03 for j ← 1 to length[A]4     do C[A[j]] ← C[A[j]] + 15 for i ← 1 to k6     do C[i] ← C[i] + C[i - 1]7 for j ← length[A] downto 18     do B[C[A[j]]] ← A[j]9     C[A[j]] ← C[A[j]] - 1

C++程式實現

#include <iostream>#include <cstring>using namespace std;void countingSort(int* A, int* B, int lengthA, int k){    int* C = new int[k + 1];    memset(C, 0, (k + 1) * sizeof(int));    for(int j = 0; j < lengthA; j++)    {        C[A[j]] = C[A[j]] + 1;    }    for(int i = 1; i < (k + 1); i++)    {        C[i] = C[i] + C[i - 1];    }    for(int j = lengthA - 1; j >= 0; j--)    {        B[C[A[j]] - 1] = A[j];        C[A[j]] = C[A[j]] - 1;    }    delete[] C;}int main(){    int arrInitial[] = {2, 5, 3, 0, 2, 3, 0, 3};    int* arrFinal = new int[8];    countingSort(arrInitial, arrFinal, 8, 5);    for(int i = 0; i < 8; i++)    {        cout << arrFinal[i] << " ";    }    cout << endl;    return 0;}
相關文章

聯繫我們

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