我真的需要一些帮助来解决这个问题,我们应该调试的这个程序有一些我找不到的错误。
该程序有一个名称数组,应该按字母顺序对名称进行冒泡排序,然后让用户搜索名称。
冒泡排序似乎没有做任何事情,搜索总是说找不到名称。
对于如何解决这个问题,一些帮助会很有帮助。谢谢。
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define NUM_OF_NAMES 8
#define NAME_SIZE 5
void printNames(char names[][5], int size);
void bubbleSortNames(char names[][5], int last);
bool binarySearchNames(char list[][5], int end, char target[], int *location);
int main()
{
char nameList[8][5]={"Zack","Jake","Jill","Seth","Eric","Beth","Hugh","Rita"},
searchText[5],
userChoice;
int searchLocation,
last = 0;
printNames(nameList, 8);
printf("\n\nLIST AFTER SORT\n\n");
bubbleSortNames(nameList, last);
printNames(nameList, 8);
printf("Would youy like to search for a name? (y/n) ");
scanf(" %c", &userChoice);
while(userChoice == 'y')
{
printf("\nPlease try and search for a name: ");
scanf("%20s", searchText);
if(binarySearchNames(nameList, 8, searchText, &searchLocation))
printf("\nThe name %s was not found. :(\n", searchText);
else
printf("\nThe name %s was found at location %d!", searchText, searchLocation);
printf("\nWould you like to search for another name? (y/n) ");
scanf(" %c", &userChoice);
}
printf("\nThank you for using this program.\n\n");
return 0;
}
/*
Prints out array of names
*/
void printNames(char names[][NAME_SIZE], int size)
{
for(int index = 0; index <= size; index++)
puts(names[index]);
return;
}
/*
Sorts names alphabetically
*/
void bubbleSortNames(char names[][NAME_SIZE], int last)
{
char temp[NAME_SIZE];
for(int current = 0; current < last; current++)
{
for(int walker = last; walker > current; walker--)
if(strcmp(names[walker], names[walker - 1]))
{
strcpy(temp, names[walker]);
strcpy(names[walker], names[walker - 1]);
strcpy(names[walker - 1], temp);
}
}
return;
}
/*
Searches for name entered
*/
bool binarySearchNames(char list[][NAME_SIZE], int end, char target[], int *location)
{
char first = 0,
last = end,
mid;
while(first <= last)
{
mid = (first + last) / 2;
if(target > list[mid])
first = mid + 1;
else if(target < list[mid])
last = mid - 1;
else
first = last + 1;
}
*location = mid;
return target = list[mid];
}