Having a struct like this:
typedef struct person {
char *name;
int age;
} person
I insert each person I create in a hash table and what I want to do is find the oldest people, like this:
Oldest People:
Austin 29
John 29
Matthew 29
I was wondering if there was a more efficent way to find the maximum age than searching the hash table twice: one to find the maximum value and the other to print all the people with the max value.
You can determine the maximum age while inserting. You need that if-clause anyways, but this way you save walking over the hash table for that.
Apart from that, you didn't say what is the key of your hash table. I assume, it is the name, since you didn't mention resolving age collisions and you mentioned the need for a second pass.
And I guess the purpose of your hash table is not just solving this problem. But if it was, I wouldn't use a hash table but just keep a list of the names with the current maximum age and reset it as soon as the maximum age changes. The list could be implemented as an array + size variable in case you know the maximum size, otherwise eg with a linked list of fixed size blocks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.