I repeat this function 2500 times in a loop for different parameters and it takes 85 seconds. What is wrong with this function? How can I improve running time? Thanks for your help.
Function:
int findBaconNumber(v * actors[], int actorCount, int index, v * visited[]){
// Bacon number is 0:
if(strcmp(actors[index]->name, "Bacon,Kevin") == 0)
return 0;
// Bacon number is infinite:
else if(actors[index]->next == NULL)
return -1;
// Otherwise, calculate:
memset(visited, NULL, sizeof(visited));
q * queue = createQueue();
v * tmp = actors[index];
v * found;
n * tmp2;
int baconNumber = 0;
int visitCount = 0;
int empty = 0;
int full = 0;
// Add first item to queue:
enqueue(queue, tmp);
visited[visitCount] = tmp;
visitCount++;
tmp->parent = NULL;
// Until queue is empty, queue is full or kevin bacon found:
while(strcmp(tmp->name, "Bacon, Kevin") != 0 && isEmpty(queue) != 1 && isFull(queue) != 1){
// Get neighbors:
if(tmp->next != NULL)
tmp2 = tmp->next;
else
tmp2 = NULL;
// Add neighbors to queue:
while(tmp2 != NULL){
if(contains(visited,visitCount+1,actors[tmp2->actorNo]) != 1){
enqueue(queue, actors[tmp2->actorNo]);
visited[visitCount] = actors[tmp2->actorNo];
visitCount++;
actors[tmp2->actorNo]->parent = tmp;
}
tmp2 = tmp2->next;
}
// Dequeue current item and skip to next item:
dequeue(queue);
// Get next item in queue:
if(getFront(queue) != NULL)
tmp = getFront(queue);
}
if(strcmp(tmp->name, "Bacon, Kevin") != 0)
return -1;
while(tmp->parent != NULL && tmp != NULL){
baconNumber++;
tmp = tmp->parent;
}
return baconNumber;
}
For Loop:
for(i=0; i<actorCount; i++){
baconNumbers[i] = findBaconNumber(actors, actorCount, i, visited);
}
EDIT: Thanks all of you for answers. This is my school project and it must be solved by breadth first search algorithm so I can not use other solutions. I profiled the code it looks like the problem is with the contains function. I use it to check if node is visited or not. Now, I am working on finding another solution for this.