[英]Sorting an array of integers in time complexity of o(n) or o(1)
能以o(n)或更少的时间复杂度对1到4(非常简单)的整数数组进行排序的最佳算法是什么?
使用基数排序 ,即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
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.