計數排序演算法(C語言實現)

來源:互聯網
上載者:User

計數排序,  比較適合數值跨度比較小的,  也就是數組中最大值減去最小值得到的值盡量小,  同時數組元素又比較多的情況下用計數排序效率比較高,同時,計數排序演算法基友穩定性。

計數排序的時間複雜度為O(n),計數排序是用來排序0到100之間的數位最好的演算法。

演算法的步驟如下:

      1.找出待排序的數組中最大和最小的元素

      2.統計數組中每個值為i的元素出現的次數,存入數組C的第i項

      3.對所有的計數累加(從C中的第一個元素開始,每一項和前一項相加)

      4.反向填充目標數組:將每個元素i放在新數組的第C(i)項,每放一個元素就將C(i)減去1

下面直接貼個C語言實現的代碼:

#include <stdio.h>#include <stdlib.h>#include <time.h>/* run this program using the console pauser or add your own getch, system("pause") or input loop */void print_arry(int *arr,int n){int i;for(i = 0; i<n; i++){printf("%d ", arr[i]);}printf("\n");}void count_sort(int *arr, int *sorted_arr, int n){int *count_arr = (int *)malloc(sizeof(int) * 100);int i; //初始化計數數組 for(i = 0; i<100; i++)count_arr[i] = 0;//統計i的次數 for(i = 0;i<n;i++)count_arr[arr[i]]++;//對所有的計數累加 for(i = 1; i<100; i++)count_arr[i] += count_arr[i-1]; //逆向遍曆源數組(保證穩定性),根據計數數組中對應的值填充到先的數組中 for(i = n; i>0; i--){sorted_arr[count_arr[arr[i-1]]-1] = arr[i-1];count_arr[arr[i-1]]--;} free(count_arr);}int main() {int n,i;printf ("待排序數組的大小 n="); scanf ("%d", &n); int *arr = (int *)malloc(sizeof(int) * n);int *sorted_arr = (int *)malloc(sizeof(int) * n);srand (time (0));for (i = 0; i<n; i++){arr[i] = rand() % 100;}printf ("隨機產生數值為0~99的數組...\n");printf ("初始化數組: ");print_arry(arr, n);count_sort(arr, sorted_arr, n);printf ("排序後的數組:"); print_arry(sorted_arr, n);return 0;system ("pause");}

 

聯繫我們

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