首页 > 代码库 > 算法导论第三版思考题8-2.e
算法导论第三版思考题8-2.e
1 COUNTING-SORT2(A,k) 2 let C[0..k] be a new array 3 for i = 0 to k 4 C[i]=0 5 for i = 1 to A.length 6 C[A[i]] = C[A[i]]+1 7 for i = 1 to k 8 C[i] = C[i] + C[i-1] 9 for i = A.length downto 1 10 while i < (j = C[A[i]) 11 exchagnge A[i] with A[j] 12 C[A[j]] = C[A[j]]-1
#include <stdio.h> #include <stdlib.h> #include<time.h> #include <memory.h> void radix2(int* arr, int len, int k) { k++; int* count_arr = (int*)malloc(sizeof(int)*k); for(int i = 0; i < k; i++) { count_arr[i] = 0; } for (int i = 0; i < len; i++) { count_arr[arr[i]]++; } for (int i = 1; i < k; i++) { count_arr[i] += count_arr[i-1]; } for (int i = len-1; i >= 0; i--) { //a[i+1 ... len-1]的元素是已经确定最终位置的元素 //求出arr[i]中元素的最终位置为j,如果i<j,则swap(a[i],a[j]), //继续寻找新arr[i]元素的最终位置,直到i>=j int j = count_arr[arr[i]] - 1; while (i < (j = count_arr[arr[i]] - 1)) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; count_arr[arr[j]]--; } } free(count_arr); } int rand_int(int max) { return (rand() % max); } void main() { int a[100] = {0}; int max = 20; srand(time(0)); for (int i = 0; i < 100; i++) { a[i] = rand_int(max); } radix2(a, 100, max); for (int i = 0; i < 100; i++) { printf("%d ", a[i]); } getchar(); }
算法导论第三版思考题8-2.e
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。