计数排序
来源:互联网 发布:搜狗排名优化 编辑:程序博客网 时间:2024/06/05 15:57
Suppose we have an input array consisting of integers, each in the range . The counting-sortalgorithm sorts using an auxiliary array of counters. It outputs a sorted version of as an auxiliary array .
The idea behind counting-sort is simple: For each , count the number of occurrences of in and store this in . Now, after sorting, the output will look like occurrences of 0, followed by occurrences of 1, followed by occurrences of 2,..., followed by occurrences of .
The first loop in this code sets each counter so that it counts the number of occurrences of in . By using the values of as indices, these counters can all be computed in time with a single for loop. At this point, we could use to fill in the output array directly. However, this would not work if the elements of have associated data. Therefore we spend a little extra effort to copy the elements of into .
The next loop, which takes time, computes a running-sum of the counters so that becomes the number of elements in that are less than or equal to . In particular, for every , the output array, , will have
Finally, the algorithm scans backwards to place its elements, in order, into an output array . When scanning, the element is placed at location and the value is decremented.The counting-sort algorithm has the nice property of being stable; it preserves the relative order of equal elements. If two elements and have the same value, and then will appear before in . This will be useful in the next section.
public class CountSort{ static int[] countSort(int[] a,int k){ //k max element in array a // the value of the element in a server as the index for c , the key point int[] c=new int[k]; for (int i = 0; i < a.length; i++) { c[a[i]]++;//same element in a will count the same element in c array } // from 1,not 0 for (int i = 1; i <k; i++) { c[i]+=c[i-1]; } int[] b=new int[a.length]; for (int i=a.length-1; i >-1; i--) { //-- operation is to process the duplicate element, the value in array is changed. pay attention b[--c[a[i]]]=a[i]; } return b; } public static int getMax(int[] arr) { int max = arr[0]; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; } public static void display(int[] R) { System.out.println(); for (int i = 0; i < R.length; i++) { System.out.print(R[i] + " "); } } public static void main(String[] args) { int[] r = { 2,3,1,5,1,6,9,9 }; display(r); int k=getMax(r)+1; int[] b=countSort(r,k); display(b); }}
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 常见的TCP定时器
- SpringBoot和微信二维码相关的部分
- 关于数据挖掘的文献综述
- 虚拟打印机adobe PDF
- 7/5:异常
- 计数排序
- 获取指定月份的最后一天
- 多分支选择结构
- java 递归显示某个文件夹下所有的文件名称
- AIC模拟信息转换
- Limcon v3.60.130320 build 130320 1CD
- Java 锁机制 synchronized
- mongodb 限制ip访问
- Android Studio使用Butterknife时出现空指针问题解决