bsearch()按名称比较

时间:2015-09-06 09:51:07

标签: c function struct bsearch

我有一个struct employee比较器和main

#define MAX_SIZE 20
typedef struct Employee{
    char name[MAX_SIZE];
    int salary;
    int experience;
} employee_t;

void main()
{
    int i;

    employee_t** employeeArray = (employee_t**)malloc(sizeof(employee_t*)*5);
    employee_t nonExstingEmployee = {"v"};

    for(i=0 ; i < 2 ; i++)
    {
        employeeArray[i] = (employee_t*)malloc(sizeof(employee_t));  //alocate each employee
        readEmployee( employeeArray[i] ); 
    }

    puts("beforesort\n");

    for(i=0; i <2 ; i++)
    {
        printEmployee(employeeArray[i]);
    }

    puts("after salary sort\n");
    qsort(employeeArray, 2, sizeof(employee_t*), compareEmployeesBySalary);
    for(i=0; i < 2 ; i++)
        printEmployee( employeeArray[i] );

    if (bsearch(&nonExstingEmployee, employeeArray, MAX_SIZE, sizeof(employee_t), compareEmployeesByName) == 0)
        puts("employee found");
    else
        puts("no employee found");

}


    int compareEmployeesBySalary(const void* a, const void* b){
            employee_t* one = *(employee_t **)a;
            employee_t* two = *(employee_t **)b;

            if (one->salary == two->salary)
                return 0;
            else if (one->salary > two->salary)
                return 1;
            else
                return -1;
    }

    int compareEmployeesByName(const void* a,const void* b)
    {
        employee_t* one = *(employee_t**)a;
        employee_t* two = *(employee_t**)b;

        if(strcmp(&one->name, &two->name) == 0)
        {
            return 1;
        }

        return 0;
    }

我需要使用bsearch比较名称(与数组中不存在的某些员工),我的qsort函数有效(按工资比较) 无论我如何为bsearch初始化员工,它总是说它不在那里(我试图先用现有员工来测试),

我应该如何初始化我的员工(或者我应该更改什么?)

[评论更新:]

这是我的readEmployee()

void readEmployee(employee_t *emp)
{
  fflush(stdin);
  printf("Please enter Employee's name:(max 19 chars)");
  scanf("%s", emp->name);

  fflush(stdin);
  printf("Please enter Employee's salary:");
  scanf("%d", &(emp->salary));

  fflush(stdin);
  printf("Please enter Employee's experience:");
  scanf("%d", &(emp->experience));
}

我正在比较nonExstingEmployee(存在于数组中以供测试)和我的employeeArray

2 个答案:

答案 0 :(得分:2)

问题很简单:按薪水qsort还有bsearch名称。它不会工作。

bsearch排序数组中执行二进制搜索。不是任何已排序的数组,而是根据搜索条件排序的数组。您必须先按名称执行qsort或坚持lsearch(即线性搜索并不依赖于之前的排序)。

答案 1 :(得分:1)

  

我应该如何初始化我的员工

您可能想告诉我们您是如何做到的(readEmployee()?),我们会对此发表评论。

  

(或者我应该改变什么?)

两个问题:

  1. 要搜索的数组不是MAX_SIZE长,而是2

    所以这一行

    if (bsearch(&nonExstingEmployee, employeeArray, MAX_SIZE, sizeof(employee_t), compareEmployeesByName) == 0)
    

    应该是

    if (bsearch(&nonExstingEmployee, employeeArray, 2, sizeof(employee_t), compareEmployeesByName) == 0)
    
  2. compareEmployeesByName()中,您传递了“错误”地址。

    这一行

    if(strcmp(&one->name, &two->name) == 0)
    

    应该是

    if(strcmp(one->name, two->name) == 0)