算法 线性排序-区间法

来源:互联网 发布:sql update数值 编辑:程序博客网 时间:2024/06/06 02:52


public class Sort {
 public static int[] sort(int[] a) {
  int min = Integer.MAX_VALUE;
  int max = Integer.MIN_VALUE;

  Map<Integer, Integer> counts = new HashMap<Integer, Integer>();

  for (int i = 0; i < a.length; i++) {
   if (a[i] < min) {
    min = a[i];
   }
   if (a[i] > max) {
    max = a[i];
   }
   if (counts.containsKey(a[i])) {
    counts.put(a[i], counts.get(a[i]) + 1);
   } else {
    counts.put(a[i], 1);
   }
  }

  int c = 0;
  for (int i = min; i <= max; i++) {
   if (counts.containsKey(i)) {
    for (int j = 0; j < counts.get(i); j++) {
     a[c++] = i;
    }
   }
  }  
  return a;
 }

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

0 0
原创粉丝点击