Hello guys!

I'm new to C language and I need help to write a program which searches specific word in text file using Binary Search and count the number of comparisons!!!

My text file consist of following data:
apple
book
clock
dog
elephant
fat
hello
key
lucky
moon
olive
paper

So far, i made program which searches word and gives the location (index) of this word in file. However, that's not what I need, I need to count the number of comparisons!

I'm currently here:

#include <stdio.h>
#include <string.h>

#define MAXSIZE 20
#define MAXLEN  20


int seq_Search(char array[][MAXSIZE], int count, char *key);	

int main(void)
{
	char target[MAXLEN];
	char words[MAXLEN][MAXSIZE];
	FILE *file;						

	
	if((file = fopen("a3.txt", "r")) == NULL){
		printf("Cannot open file\n");
	} 

	else{
		
		int i = 0;
		
		while(!feof(file)){  
			fscanf(file, "%s", words[i]);
			}
			i++;
		}


	printf("\n\nInput: ");
	scanf("%s", target); 


	
			int location = seq_Search(words, 15, target);
			
			if((strcasecmp(words[location], target)) == 0){
				printf("\nWord %s found", target);
				printf("Location: %d\n", location);
				}
			else{
				printf("\nWord %s cannot be found   ", target);
				printf("Location: %d\n", location);
				}
		

	}
	return 0;
}

int seq_Search(char array[][MAXSIZE], int end, char *key)

{	
	int mid;
	int first = 0;
	int last = end;
	 
	while(first <= last){
		mid = (first + last) / 2;

		if(strcasecmp(array[mid], key) < 0)
			{
				first = mid + 1;
			}

		else if(strcasecmp(array[mid], key) > 0)
			{
				last = mid - 1;
			}

		else 
			break;
	
	}
	return mid; 
}

Thank you in advance!

PS: sorry for my poor english!

Save the result of the string compare so you wont do it twice. Then just increment a counter.

int seq_Search(char array[][MAXSIZE], int end, char *key)

{	
	int mid;
	int first = 0;
	int last = end;
        int cmp;
	 
	while(first <= last){
		mid = (first + last) / 2;
                cmp = strcasecmp(array[mid], key);
                g_Count++; 

		if(cmp < 0)
			{
				first = mid + 1;
			}

		else if(cmp) > 0)
			{
				last = mid - 1;
			}

		else 
			break;
	
	}
	return mid; 
}

Save the result of the string compare so you wont do it twice. Then just increment a counter.

int seq_Search(char array[][MAXSIZE], int end, char *key)

{	
	int mid;
	int first = 0;
	int last = end;
        int cmp;
	 
	while(first <= last){
		mid = (first + last) / 2;
                cmp = strcasecmp(array[mid], key);
                g_Count++; 

		if(cmp < 0)
			{
				first = mid + 1;
			}

		else if(cmp) > 0)
			{
				last = mid - 1;
			}

		else 
			break;
	
	}
	return mid; 
}

Thank you very much for your reply, but it seems the code that you showed me didn't work for me! :(((((

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.