線性時間排序-計數排序

來源:互聯網
上載者:User

計數排序:

基本思想:對每一個輸入元素x,確定出小於x的元素個數。有了這一資訊,就可以把x直接放到它在最終輸出數組中的位置上。例如,如果有17個元素小於x,則x就屬於第18個輸出位置。

 

時間複雜度:O(k+n),n為輸入元素個數,假設所有輸入元素都不大於k。

空間方面則額外用到了兩個數組,一個用來統計,一個用來存放排序結果。所以也是O(n+k) ;

 

#include<stdio.h>#define N 50void CountingSort(int *A,int *B,int n,int k) ;int main(void){int i,n,k ;int A[N],B[N] ;freopen("in.txt","r",stdin) ;while(scanf("%d%d",&n,&k) != EOF ){for(i = 1 ; i <=n ; ++i){scanf("%d",&A[i]) ;}printf("You have input the List:\n") ;for(i = 1 ; i <=n ; ++i){printf("%-3d",A[i]) ;}CountingSort(A,B,n,k) ;printf("\nAfter Sort:\n") ;for(i = 1 ; i <= n ; ++i){printf("%-3d",B[i]) ;}printf("\n\n") ;}return 0 ;}void CountingSort(int *A,int *B,int n,int k) {int i ;int C[N] ;for(i = 0 ; i <= k ; ++i){C[i] = 0 ; }for(i = 1 ; i <= n ; i++){C[A[i]]++ ; }for(i = 1 ; i <= k ; i++ ){C[i] += C[i-1] ;}for(i = n ; i >= 1 ; --i){B[C[A[i]]] = A[i] ; ;C[A[i]]-- ; }}

 

聯繫我們

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