标签:style blog color os java ar for div sp
算法导论:
计数排序假设被排序的元素都在范围[0, k]中,k为正整数,当k=O(n)的时候,计数排序的运行时间为O(n),计数排序是稳定的
代码:
1 package sorts; 2 3 import java.util.Arrays; 4 import java.util.Random; 5 6 public class CountingSort { 7 /** 8 * @param a the target array 9 * @param b the array to store the result of the sort 10 * @param k in the target array, each element is in the range [0, k] 11 * */ 12 public static void sort(int[] a, int[] b, int k) { 13 int[] c = new int[k+1]; // counting array 14 for (int i = 0; i < k; i++) { 15 c[i] = 0; 16 } 17 for (int i = 0; i < a.length; i++) { 18 ++c[a[i]]; // c[x] is the number of elements in ‘a‘ equal to x. 19 } 20 for (int i = 1; i <= k; i++) { 21 c[i] = c[i] + c[i-1]; // c[x] is the number of elements in ‘a‘ no more than x. 22 } 23 for (int i = a.length - 1; i >= 0; i--) { 24 b[c[a[i]]-1] = a[i]; // convert to index, must subtract 1 25 --c[a[i]]; 26 } 27 } 28 29 // test 30 public static void main(String[] args) { 31 Random random = new Random(); 32 int num = 10; 33 int bound = 100; 34 int[] a = new int[num]; 35 int[] b = new int[num]; 36 for (int i = 0; i < num; i++) { 37 a[i] = random.nextInt(bound); 38 } 39 CountingSort.sort(a, b, bound-1); 40 System.out.println(Arrays.toString(b)); 41 } 42 }
标签:style blog color os java ar for div sp
原文地址:http://www.cnblogs.com/qrlozte/p/3963203.html