计数排序(导入自原博客)

计数排序

 

As the original array is A, without sorting, we define twoadditional arrays B and C. C is used as a storage which helps toclarify the position of each number of array A in array B.

 

Firstly, we use C to store the frequency of each number of arrayA appears. Then we plus each number and the onesbefore it, useing the results to refillin each position of array C.The index of array Cis just the value of arrayA, and the the pointing value ofthe index in array C implies the final position of each number ofarray A in array B.

 

Counting sort is stable, and usually applies in the situationthat we can be sure the value of the max number. It has somelimitations, for example, the numbers to be sorted must benonegtive.

 

Following is one implementation of counting sort algorithm,using Java.

 

 

public void Counting_Sort(int[] A, max){

  int len= A.length; 

  int[] B = new int[len]; //B is the finalarray

  int[] C = new int[max + 1];// C is thestorage, with each number initialed with 0

  // the frequency of the appearence of eachnumber in array A

  for (int i = 0; i < n; i++){

     C[A[i]] = C[A[i]] + 1;

  }

  // the number thatsatisifying the condition of i <=max;

  // each number plus with the ones beforeit

  for (int i = 1; i <= max; i++){

    C[i] = C[i] + C[i - 1];

  }

  // put the value of A into the right positionof B

  for (i = n - 1; i> 0; i --){

    B[C[A[i]]] = A[i];

    C[A[i]] = C[A[i]] - 1; // encounting the same value

  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值