Bucket Sorting
Posted: Wed Feb 23, 2011 7:15 am
Hi friends,
I just written an implementation of Bucket Sorting for strings,
i need your opinions to improve it.
I think
this needs some optimize, the idea is to sorting an array of strings by divided them
to buckets ; each bucket has a label with alphabetical letter. e.g bucket #1 holds "a" strings.
Cheer$,
a.T.D
I just written an implementation of Bucket Sorting for strings,
i need your opinions to improve it.
Code: Select all
struct Node {
char *Data;
struct Node *Next;
};
struct Node * BucketSort(struct Node *Array){
// Time Complexity: Best Case : Theta N
// Average Case : Theta N
// Worst Case : Theta N*N (ie Insertion Sort)
#define size 26 // a-z
struct Node **buckets, *sortedList=NULL;
int i,k;
buckets=(struct Node **)malloc(sizeof(struct Node *) * size);
for(i=0;i<size;++i){ // Init Buckets
buckets[i]=NULL;
}
///////// Drop Items into Buckets ///////////////
struct Node *p = Array ;
while(p){
int pos;
pos = p->Data[0]-'a' ; // <----------
buckets[ pos ] = creatNode( p->Data , buckets[pos] );
p=p->Next;
}
//////// Sort Buckets using Insertion Sort /////////////
for(i=0;i<size;++i){
if(buckets[i])
buckets[i]=InsertionSort(buckets[i]);
}
///// concatenate the buckets ////////
for(i=0;i<size;++i){
struct Node *currentBucket = buckets[i] ;
while( currentBucket ){
sortedList = creatNode( currentBucket->Data , sortedList);
currentBucket = currentBucket->Next;
}
}
//Release All Memory Allocted
for(i=0;i<size;++i){
nodeFree( buckets[i] );
}
free(buckets);
return sortedList ;
}
Code: Select all
pos = p->Data[0]-'a' ; // <----------
to buckets ; each bucket has a label with alphabetical letter. e.g bucket #1 holds "a" strings.
Cheer$,
a.T.D