My question is related to the task from CS50, pset5. For those who do not know about this, I will try to explain. Nothing special. I just need to make a function that will go into the dictionary dictionary (it was written earlier, all the words in this file are capitalized), which contains more than 20K words and sort them somehow. I made a simple and naive algorithm by creating a hash table that sort words, depending on their first letters. And I went through all the checks on the CS50, so my program works well. But compared to the course, one is too slow. The lead time for staff is 0.1 s, but for mine - 5.0 s - 7.0 s. What can I improve in this code to make it faster? Or should I completely change everything? I have no experience in optimization, because I just started to learn. It would be great to learn from any of you =) Thanks in advance!
#define LENGTH 46
#define ALPHALENGTH 26
typedef struct node {
char word[LENGTH +1];
struct node *next;
} node;
node *hashTable[ALPHALENGTH];
bool load(const char *dictionary) {
FILE *f = fopen(dictionary, "r");
if (f == NULL) {
return false;
}
char word[LENGTH + 1];
int hash = 0;
for (int i = 0; i < ALPHALENGTH; i++) {
hashTable[i] = NULL;
}
while (fscanf(f, "%46s", word) == 1) {
hash = tolower(word[0]) - 'a';
node *new_node = malloc(sizeof(node));
strcpy(new_node->word, word);
if (hashTable[hash] == NULL) {
new_node->next = NULL;
hashTable[hash] = new_node;
} else {
node *ptr = hashTable[hash];
do {
if (ptr->next == NULL) {
break;
}
ptr = ptr->next;
} while (true);
ptr->next = new_node;
new_node->next = NULL;
}
}
fclose(f);
return true;
}