[英]Why is Radix Sort's Big O isn't quadratic?
function getDigit(num, i) {
return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;
}
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
function radixSort(nums){
let maxDigitCount = mostDigits(nums);
for(let k = 0; k < maxDigitCount; k++){
let digitBuckets = Array.from({length: 10}, () => []);
for(let i = 0; i < nums.length; i++){
let digit = getDigit(nums[i],k);
digitBuckets[digit].push(nums[i]);
}
nums = [].concat(...digitBuckets);
}
return nums;
}
So this is the radix sort code that I learned.这就是我学到的基数排序代码。 But if you look at radixSort function, for loops in there are nested, which from what I learned means that the Big O of radix sort is O(n 2).但是,如果您查看 radixSort function,其中的 for 循环是嵌套的,据我所知,这意味着基数排序的大 O 是 O(n 2)。 But according to the material I learned, it says that the time complexity of radix sort is O(nk).但是根据我学到的材料,它说基数排序的时间复杂度是O(nk)。 n being the length of array and k being the number of digits(average). n 是数组的长度,k 是位数(平均)。 I can't figure out why it's not O(n 2).我不知道为什么它不是 O(n 2)。
Big O notation , in computer science, is used to classify algorithms according to how their run time or space requirements grow as the input size grows.在计算机科学中,大 O 表示法用于根据算法的运行时间或空间需求随着输入大小的增长而增长来对算法进行分类。
Radix sort has linear complexity O(nk) .基数排序具有线性复杂度O(nk) 。 This is because k is the constant number (nuber of digits) and n can grow (length of array).这是因为k是常数(位数),并且n可以增长(数组的长度)。
k affects the slope of the function, but it is far from O(n 2 ) complexity (graph n=1 to 30): k影响 function 的斜率,但它远不是 O(n 2 ) 复杂度(图 n=1 到 30):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.