发布网友 发布时间:2022-04-22 11:08
共2个回答
热心网友 时间:2023-10-12 00:21
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EMPCNT 10
struct employee
{
int id;
char name[16];
};
void sort( struct employee *e )
{
int i,j;
struct employee temp;
for( i=0; i<EMPCNT; i++ )
{
for( j=i+1;j<EMPCNT;j++ )
{
if ( e[j].id < e[i].id )
{
/* swap*/
temp = e[i];
e[i] = e[j];
e[j] = temp;
}
}
}
}
int search( struct employee *e, int id )
{
int low, high, mid;
low = 0;
high = EMPCNT - 1;
while( low <= high )
{
mid = ( low+high ) / 2;
if ( id < e[mid].id )
high = mid - 1;
else if ( id > e[mid].id )
low = mid + 1;
else
return mid;
}
return -1;
}
void main()
{
struct employee e[EMPCNT];
int i, id=0, m=-1;
for( i=0; i<EMPCNT; i++ )
{
printf( "输入第 %d 员工的员工号,姓名:", i+1 );
scanf( "%d %s", &e[i].id, e[i].name );
fflush( stdin );
}
sort( e );
for( i=0; i<EMPCNT; i++ )
printf( "%d %s\n", e[i].id, e[i].name );
printf("要查找的员工号:" );
scanf( "%d", &id );
fflush( stdin );
m = search( e, id );
if ( m < 0 )
printf( "%d 未找到\n", id );
else
printf( "%d %s\n", e[m].id, e[m].name );
getchar();
}
热心网友 时间:2023-10-12 00:22
这个我没有测试过,大概的轮廓我写好了
#include<stdio.h>
#include<string.h>
void sort(char name[][20], int number[])
{
int i, j, temp;
char *index=NULL;
for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
{
if(number[j]<number[j+1])
{
strcpy(index, *name);
strcpy(*name, *name+1);
strcpy(*name, index);
temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
}
}
void search(int num, char name[][20], int number[])
{
int n=10;
while(number[n/2]!=num)
{
n=number[n/2]>num?(n+n/2+1):(n/2-1);
}
printf("%d %s\n", n/2, *name+n/2);
}
int main(void)
{
int i, num;
int number[10];
char name[10][20];
for(i=0;i<10;i++)
scanf("%s%d", name[i], &number[i]);
sort(name, number);
scanf("%d", &num);
search(num, name, number);
return 0;
}