DSAA之Radix Sort(桶排序)(二)

1. Bucket sort

  • If we have n integers in the range 1 to m (or 0 to m - 1) , we can use this information to obtain a fast sort known as bucket sort.
  • We keep an array called count, of size m, which is initialized to zero. Thus, count has m cells (or buckets), which are initially empty.
  • When a i is read, increment (by one) count[ a i ]. After all the input is read, scan the count array, printing out a representation of the sorted list. This algorithm takes O(m + n);

  桶排序的概念很简单,并且时间复杂度也很好证明,因为需要做两样事情:

  • 遍历n个数,将n个数放置相应的桶中。
  • 遍历所有的桶,打印出来结果。

    所以其时间复杂度为 O ( m + n )

2. Radix sort

  • The natural algorithm would be to bucket-sort by the most significant “digit” (digit is taken to base n), then next most significant, and so on. That algorithm does not work, but if we perform bucket sorts by least significant “digit” first, then the algorithm works.按照最低有效位进行处理,就可以得到正确的结果
  • Of course, more than one number could fall into the same bucket, and, unlike the original bucket sort, these numbers could be different, so we keep them in a list.之前的桶排序,重复元素,只是相应的桶位置的计数值增加。
    • Notice that all the numbers could have some digit in common, so if a simple array were used for the lists, then each array would have to be of size n, for a total space requirement of Θ ( n 2 ) .使用数组代替链表,假设n个数全部相同的极端情况,此时需要每个cell都有一个n大小的数组,所以空间复杂度非常大。
    • The running time is O ( p ( n + b ) ) where p is the number of passes, n is the number of elements to sort, and b is the number of buckets.

  DSAA给了一个10个数的简单例子:


  1. 个位排序
    这里写图片描述

  1. 十位排序
    这里写图片描述

  1. 百位排序
    这里写图片描述

3. 最后

  上一节中提到的,任何仅仅依靠比较的排序算法,其至少需要 n l o g n 次比较,感觉似乎桶排序已经违反了这个准则,其实并没有。笔者认为桶排序是典型的以空间换时间的算法,每次安排元素去某个桶时,间接的已经同其他所有的桶(元素)进行了对比:

By incrementing the appropriate bucket, the algorithm essentially performs an m-way comparison in unit time.

猜你喜欢

转载自blog.csdn.net/lovestackover/article/details/80442599