radix sort (using counting sort as the key subr...

radix sort主要分爲兩種,least significant digit radix sort 和 most significant digit radix sort。其應用場景,不單單是整數的排序。 radix sort並非原地排序算法,它的空間複雜度是O(kn)。radix sort的時間複雜度是O(kn),n是key的數目,k是每一個key的digit數目。 對整數排序,一般使用LSD radix sort,由於這樣正好是位數多的會排在後面,好比1,2,11通過排序後是1,2,11。若是是用MSD radix sort來排序,就是1,11,2. 對字符串排序(好比單詞),用MSD radix sort,由於這樣證號是按字典排序的。如a,ab,b經MSD排序後是a,ab,b;若是用LSD來排序,就是a,b,ab。 對於如下程序,有一點要注意:程序中的數組是從0開始的,而不是intro-to-algo中一般的1開始的數組示例,因此conting sort subroutine要稍微改一下。 /**  * function: counting_sort_byte  * @part: 0 1 2 3 -> [byte3][byte2][byte1][byte0] of an integer  *  * sort a[begin, end) by byteN  **/ void counting_sort_byte(int A[], int begin, int end, int range, int part) {     assert(part<=3 && part >=0);     int *aux = (int*)malloc_c(sizeof(int)*range);     int *b = (int*)malloc_c(sizeof(int)*(end-begin));     unsigned *a = (unsigned*)malloc_c(sizeof(unsigned) * (end-begin)); /* store the value of byteN of A */     int i, j;     for (i=0; i<range; i++)     {         aux[i] = 0;     }     for (j=begin; j<end; j++)     {         a[j] = (unsigned) ( (A[j]>>(part*8))&0xFF ); /* a[j] belongs to [0, range) */         aux[a[j]] += 1;     }     for (i=1; i<range; i++)     {         aux[i] = aux[i-1] + aux[i];     }     for (j=end-1; j>=begin; j--)     {         b[aux[a[j]]-1] = A[j];         aux[a[j]] -= 1;     }     for (j=begin; j<end; j++)     {         A[j] = b[j];     }     free(a);     free(b);     free(aux); } /**  * function: radix sort  *  * use counting_sort as key subroutine;  * 4 parses of counting sort: counting_sort(A, begin, end, 256, i) where i = 0,1,2,3  **/ void radix_sort(int A[], int begin, int end) {     for (int i=0; i<4; i++)         counting_sort_byte(A, begin, end, 256, i); }
相關文章
相關標籤/搜索