排序之线性排序(counting sort, radix-sort, bucket-sort)

 Counting Sort

Count sort的约束是:排序key可用有限的k描述出来。

Count sort有约束的情况下,O(n)的复杂度,stable排序。空间复杂度也为O(n)

 

Counting-Sort(A, B, k)

         For i <- 0 to k:

                   Do C[i] <- 0

For j <- 1 to len(A):

                   Do C[A[j]] <- C[A[j]] + 1

        

         For I <- 0 to k

                   Do C[i] <- C[i] + C[i-1]

         For j <- len(A) to 1:

                   Do B[C[A[j]]] <- A[j]

                   C[A[j]] <- C[A[j]] – 1

 

To make sure sorting is stable, it is very important

Radix Sort

Each elem contain d digits,对count-sort的应用。

每个element包含dchild-element,每个child-element可用k空间描述。K[0-9] or [a-z]

Radix – Sort(A, d):

         For I <- 1 to d:

                  Do use stable sort to sort array on digit i

O(d(n+k))

 

比如:有长度为N个长度为d的字符串,按照字典序排序。

采用快排,复杂度约为 O(kNlog(N))

采用radix sort,复杂度为O(d*N)

 

Bucket sort

按照规则将key映射到指定位置,key->valuevaluelist

value依次插入对应的list。对每个list排序即可。

你可能感兴趣的:(c/c++,算法和数据结构)