algorithm – 计数排序的运行时间

我试图了解计数排序的运行时间.在我的笔记中,它说,假设数组A的大小是n,k是每个数字出现的次数,

 Counting-Sort(A,k) {
   for (i=1; i <= k; i++) // initialize number counters to 0
       times[i] = 0;

   for (j=1; j <= length[A]; j++) // decide how many times each
       times[A[j]]++;                  // number appears in the input

  // form the sorted array
  m=1;
    for ( i=1; i <= k; i++)    // consider each number in the range
         for ( j=1; j <= times[ i ]; j++) { // generate that number in 
            A[m]=i;                   // the output as many times as
            m++;                      // it occurs in the input
         }
  }

Let ti denote the number of times the inner loop iterates for each i. When we look at the nested for loops at the bottom of the code, note that, every time the inner loop is iterated, we are placing a new number into its correct place in the output array.
Hence: sum ti (from i=1 to k) = n.

我不明白为什么这个总和等于n.外循环迭代k次,内循环最多迭代n次,因此它必须是O(nk).有人可以解释一下吗?谢谢

最佳答案 正如你可以看到的循环

m=1;
for ( i=1; i <= k; i++)    // consider each number in the range
     for ( j=1; j <= times[ i ]; j++) { // generate that number in 
        A[m]=i;                   // the output as many times as
        m++;                      // it occurs in the input
     }

它的复杂性将等于内循环体的执行次数.当i = 1时,当i = 2 =>时执行次数[1]次.时间[2]次,所以,当i = k时,乘以[k]次.因此,总体内部执行次数[1]次[2] …次[k]次,并且该和等于n,因为每个元素被计数一次.

点赞