算法 线性排序-计数排序

来源:互联网 发布:游戏服务端 python 编辑:程序博客网 时间:2024/05/16 07:39



public class BaseSort {
 public static int[] sort(int a[]) {
  int max = Integer.MIN_VALUE;
  for (int i = 0; i < a.length; i++)
   if (a[i] > max)
    max = a[i];

  int[] count = new int[max + 1];
  for (int i = 0; i < a.length; i++) {
   count[a[i]]++;
  }

  for (int i = 1; i < count.length; i++) {
   count[i] += count[i - 1];
  }

  int[] b = new int[a.length];
  for (int i = a.length - 1; i >= 0; i--) {
   b[count[a[i]] - 1] = a[i];
   count[a[i]]--;
  }

  return b;
 }

 public static void main(String[] args) {
  int[] a = { 4, 3, 2, 5, 3, 6, 2, 10, 8, 12, 6, 7 };
  int[] b = sort(a);
  System.out.println(Arrays.toString(b));
 }
}

0 0
原创粉丝点击