为什么Radix排序的指令数量大于C中的快速排序?

时间:2015-04-05 22:12:29

标签: algorithm

我在C中设置了2种排序算法,基数排序和快速排序功能 但是当我用gdb检查那些函数时,结果表明快速排序的指令数量少于基数排序。感觉更快......
据我所知,Radix sort是最快的排序算法。
Belows是我的维基分类代码 1.快速排序

void q_sort(int numbers[], int left, int right)
 {
   if(left == right) return;
   int pivot, l_hold, r_hold;
   l_hold = left;
   r_hold = right;
   pivot = numbers[left];

   while (left < right)
   {
     while ((numbers[right] >= pivot) && (left < right))
       right--;

     if (left != right)
     {
       numbers[left] = numbers[right];
       left++;
     }

     while ((numbers[left] <= pivot) && (left < right))
       left++;

     if (left != right)
     {
       numbers[right] = numbers[left];
       right--;
     }
   }

   numbers[left] = pivot;
   pivot = left;
   left = l_hold;
   right = r_hold;

   if (left < pivot)
     q_sort(numbers, left, pivot-1);
   if (right > pivot)
     q_sort(numbers, pivot+1, right);
 }

2.Radix sort

/**
 * @data  array
 * @size  the number of array
 * @p  cipher of the biggest number
 * @k  notation( in case of decimal, it is 10)

 */
void rxSort(int *data, int size, int p, int k) {
     int *counts,
     *temp;
     int index, pval, i, j, n;
     if ( (counts = (int*) malloc(k * sizeof(int))) == NULL )
          return;
     if ( (temp = (int*) malloc(size * sizeof(int))) == NULL )
          return;
     for (n=0; n<p; n++) {
          for (i=0; i<k; i++)
               counts[i] = 0; // initialize

          // n:0 => 1,  1 => 10, 2 => 100
          pval = (int)pow((double)k, (double)n);
          for (j=0; j<size; j++) {
               // if the number is  253
               // n:0 => 3,  1 => 5, 2 => 2
               index = (int)(data[j] / pval) % k;
               counts[index] = counts[index] + 1;
          }
          for (i=1; i<k; i++) {
               counts[i] = counts[i] + counts[i-1];
          }
          for (j=size-1; j>=0; j--) {
               index = (int)(data[j] / pval) % k;
               temp[counts[index] -1] = data[j];
               counts[index] = counts[index] - 1;
          }

          memcpy(data, temp, size * sizeof(int));
     }
}

以下有一些限制 1.数组的大小应设置为256 2.数字范围为0~64 3.它使用不同的阵列运行四次。

当我测试时,我将数组的大小设置为50
然后,instrunctions的数量 基数:15030
快速:7484
快速获胜...... T_T ..对Radix如此悲伤......快速排序是否更快?

1 个答案:

答案 0 :(得分:1)

Quicksort通常是排序数组时的最佳选择,尤其是当您没有关于数字范围的信息且数组非常大时。这是因为qsort具有与其输入大小成比例的预期时间复杂度乘以该大小的对数O(nlogn),这是使用基于比较的算法可以获得的最佳值。此外,它有一个小的隐藏常数因素,并在其中进行排序。基数排序不与比较排序,您需要有一些关于输入大小(n)和每个数字的平均位数(k)的信息,因为它的时间复杂度与k * n成正比。

在你的情况下你有一个很小的数组来进行测试,因此两种算法的行为之间的任何可观察的差异都是渐近无关的。 Quicksort获胜是因为,如上所述,它有一个隐藏在O(nlogn)中的小的常数操作因子。如果你尝试在一个小数组上运行插入排序和合并排序,尽管在最坏的情况下InsSort有O(n ^ 2)和MergeSort O(nlogn),插入排序很可能会更快,同样原因如上。 但是请确保如果你在一个10 ^ 8数组的数组上尝试它们,结果会发生很大变化。 另外请记住,没有<​​strong>最好的排序算法这样的东西,你只需要看每次哪一个更适合你问题的本质。 :)