I have a struct member that holds lots of string elements. What I want is to iterate the whole member of the struct and count only different elements (diff last names).
struct log {
char *last;
};
...
struct log *l
l->last = last_name; // loading *last member with data coming from last_name var
...
What would be a good way to compare and count unique elements currently on *last?
Any help will be appreciate it.
Sort your array on the
last_namekey. Duplicates will be next to each other.Do a linear sweep through the array, checking how many entries after the current item have the same last name. Increment your counter once for all these duplicates. Increment your read-head to the first distinct entry.
For an array of size
n:O(n lg n) + O(n) = O(n lg n)operations, assuming anO(n lg n)sort routine.