什么是最佳算法,可以将整数数组从1到4(非常简单)排序,时间复杂度为o(n)或更小?
答案 0 :(得分:2)
使用Radix Sort,即O(n)
public void radixsort(int[] input) {
final int RADIX = 10;
// declare and initialize bucket[]
List<Integer>[] bucket = new ArrayList[RADIX];
for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<Integer>();
}
// sort
boolean maxLength = false;
int tmp = -1, placement = 1;
while (!maxLength) {
maxLength = true;
// split input between lists
for (Integer i : input) {
tmp = i / placement;
bucket[tmp % RADIX].add(i);
if (maxLength && tmp > 0) {
maxLength = false;
}
}
// empty lists into input array
int a = 0;
for (int b = 0; b < RADIX; b++) {
for (Integer i : bucket[b]) {
input[a++] = i;
}
bucket[b].clear();
}
// move to next digit
placement *= RADIX;
}
}
code
Ref