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));
}
}
算法 线性排序-区间法
最新推荐文章于 2021-06-25 13:50:10 发布