基数排序
#include<stdlib.h> #include <strings.h> #include<stdio.h> #include<math.h> typedef struct bucket_item s_bucket_item; struct bucket_item{ int value; s_bucket_item * next; }; typedef struct bucket s_bucket; struct bucket{ s_bucket_item * head; s_bucket_item * tail; }; s_bucket_item * all_bucket_item_point; s_bucket * bucket_array; void init_bucket(int array_size,int max_byte_value){ all_bucket_item_point = (s_bucket_item *)malloc(array_size*sizeof(s_bucket_item)); bucket_array=(s_bucket *)malloc((max_byte_value + 1)*sizeof(s_bucket)); } void reset_bucket(int array_size,int max_byte_value){ bzero(all_bucket_item_point,array_size*sizeof(s_bucket_item)); bzero(bucket_array,(max_byte_value + 1)*sizeof(s_bucket)); } void put_bucket(int * values,int array_size,int byte_position){ int i = 0; for(;i < array_size; i++){ int byte_value = get_byte_value(*(values + i),byte_position); (all_bucket_item_point+i)->value=*(values+i); (all_bucket_item_point+i)->next=NULL; if((bucket_array + byte_value)->head == NULL){ //this bucket is empty (bucket_array + byte_value)->head = all_bucket_item_point+i; (bucket_array + byte_value)->tail= all_bucket_item_point+i; }else{ (bucket_array + byte_value)->tail->next = all_bucket_item_point+i; (bucket_array + byte_value)->tail = all_bucket_item_point+i; } } } void pushback_bucket_to_original_array(int * values,int max_byte_value){ int i=0,j=0; for(;i<max_byte_value + 1;i++){ while((bucket_array + i )->head!=NULL){ *(values + j) = (bucket_array + i )->head->value; (bucket_array + i )->head = (bucket_array + i )->head->next; j++; } } } int get_byte_value(int number,int byte){ if(byte < 1) return 0; int i=1; for(;i<byte;i++){ number = floor(number / 10); } return number % 10; } void dosort(int * values,int array_size,int byte_count,int max_byte_value){ init_bucket(array_size,max_byte_value); int byte_position=1; for(;byte_position<=byte_count;byte_position++){ put_bucket(values,array_size,byte_position); pushback_bucket_to_original_array(values,max_byte_value); } return ; } void printArray(int * values,int array_size){ int i = 0; for(;i<array_size;i++){ printf("%d ",*(values + i)); } } int main(int argc,char ** argv){ int values[] = {1,0,10,20,3,5,6,4,9,8,12,17,34,11}; init_bucket(14,9); dosort(values,14,2,9); printArray(values,14); free(all_bucket_item_point); free(bucket_array); printf("\n"); }