线性时间排序之计数排序(算法导论8.2)

本文介绍了一种稳定的排序算法——计数排序。该算法适用于输入元素为整数且范围有限的情况,能在线性时间内完成排序。文章详细解释了计数排序的工作原理,并提供了一个使用C++实现的具体例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Counting sort assumes that each of then input elements is an integer in the range 0 to k, for some integer k. When k =O(n), the sort runs in Θ(n) time.

The basic idea of counting sort is to determine, for each input elementx, the number of elements less than x. This information can be used to place element x directly into its position in the output array. For example, if there are 17 elements less thanx, then x belongs in output position 18. This scheme must be modified slightly to handle the situation in which several elements have the same value, since we don't want to put them all in the same position.

In the code for counting sort, we assume that the input is an arrayA[1 n], and thus length[A] =n. We require two other arrays: the array B[1 n] holds the sorted output, and the arrayC[0 k] provides temporary working storage.

COUNTING-SORT(A, B, k)
 1  for i  0 to k
 2     do C[i]  0
 3  for j  1 to length[A]
 4     do C[A[j]]  C[A[j]] + 1
 5   C[i] now contains the number of elements equal to i.
 6  for i  1 to k
 7     do C[i]  C[i] + C[i - 1]
 8   C[i] now contains the number of elements less than or equal to i.
 9  for j  length[A] downto 1
10     do B[C[A[j]]]  A[j]
11        C[A[j]]  C[A[j]] - 1
代码,VS2008编译通过
 

#include<iostream> #include<time.h> using namespace std;

void initArray(int arr[], int n, int top){  srand(time(NULL));  for(int i=0; i<n; i++){   arr[i] = rand()%top;  } }

void printArray(int arr[], int n){  for(int i=0; i<n; i++){   cout <<arr[i]<<" ";  }  cout<<endl; }

void countSort(int arr[], int n, int max){//max for the number one larger than max  int* B = (int*) malloc(n*sizeof(int));//store the result  int * C = (int*) malloc(max*sizeof(int));//store the counter  memset(C,0,max*sizeof(int));  for(int i=0; i<n; i++){//counter number   C[arr[i]]++;  }  //counter <=  for(int i=1; i<max;i++){   C[i] += C[i-1];  }

 for(int i=n-1; i>0; i--){   B[C[arr[i]]-1] = arr[i];   C[arr[i]]--;//handle for equal  }  memcpy(arr,B,n*sizeof(int));  free(B);  free(C);

}

void main(){  const int AD = 20;  int arr[AD];  initArray(arr,AD,400);  printArray(arr,AD);

 countSort(arr,AD,400);  printArray(arr,AD);  exit(0); }

 
欢迎批评指正,共同进步
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值