Since this is an assignment I won't provide a complete answer, merely some ideas on how to proceed.
Since the strings can be any length you need to use an O(n) sorting algorithm.
One such algorithm is bucket sort.
So how do we arrange the buckets for variable length strings?
Create 256 buckets for the first character.
Let each bucket have a counter + a set of 256 buckets for the second character and so on.
Important note: Don't create any bucket set until you need to or the memory consumption will be infinite. Let an empty bucket set be NULL
When we have the bucket system set up. How do we sort a word into the bucket system?
Let's say we have the word Yes
.
First character is Y
so we go to the top level bucket set. The set is NULL
so we create the top level and select bucket 'Y'
.
Next character is e
. The bucket set under Y
is NULL
so we create the set and select bucket 'e'
.
Next character is s
. The bucket set under Ye
is NULL
so we create the set and select bucket 's'
.
The string ends. Increase the count for the current bucket Y->e->s
.
Note that the task will be simpler if you use unsigned char
, because then you can use the value directly as an index into an array of length 256
.
The bucket
struct could look like this:
typedef struct bucket {
int count;
struct bucket *next; // points to NULL or array of 256 buckets.
} bucket;
Time Complexity:
The maximum amount of work for each character is:
end of string check + NULL check + ((allocation and initialization of array of 256 buckets (I would use calloc
for this) or (increase one bucket count)) + increase loop variable.
Memory Usage
Here comes the disadvantage of bucket sort. It uses a lot of memory if you need many buckets, and this solution will use quite a number.