1.编写递归函数,实现在从小到大有序的整型数组中进行二分检索,找到数据则返回所在的下表,未找到数据则返回-1,注:数组的下标从0开始。
#include <stdio.h>
int search(int *a,int left,int right,int key) {
while(left<right) {
int mid=(left+right)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
return search(a,mid+1,right,key);
else
return search(a,left,mid-1,key);
}
return -1;
}
2.每个教师信息卡片包括教工号,姓名,性别,入职年份四项。定义存储教师信息的单链表的结点类型;编写函数,由文件in.txt依次读入n(n>=0)个教师的信息(假定文件中存储信息于结构体信息格式对应),创建一个用于存储教师信息的单链表。
#include <stdio.h>
#include <stdlib.h>
typedef struct date {
int day,month,year;
} date;
typedef struct teacher {
int num;
char name[20];
int sex;
int year;
struct teacher *next;
} teacher;
struct teacher *create(int n) {
FILE *file;
if((file=fopen("in.txt","r"))==NULL) {
printf("open error");
exit(0);
}
struct teacher *head=(struct teacher *)malloc(sizeof(struct teacher));
head->next=NULL;
for(int i=0; i<n; i++) {
struct teacher *p=(struct teacher *)malloc(sizeof(struct teacher));
fscanf(file,"%d %s %d %d",&p->num,&p->name,&p->sex,&p->year);
p->next=head->next;
head->next=p;
}
return head;
}
3.编写函数,将上题所建单链表按照入职年份从小到大,入职年份相同的结点按照教工号从小到大的顺序对单链表进行排序,并将排好序的信息存储到out.txt中
#include <stdio.h>
#include <stdlib.h>
typedef struct date {
int day,month,year;
} date;
typedef struct teacher {
int num;
char name[20];
int sex;
int year;
struct teacher *next;
} teacher;
int cmp(struct teacher *a,struct teacher *b) {
if(a->year==b->year)
return a->num<b->num;
return a->year<b->year;
}
struct teacher *sort(struct teacher *head) {
struct teacher *dummyhead=(struct teacher *)malloc(sizeof(struct teacher));
dummyhead->next=NULL;
struct teacher *pre=dummyhead,*p=head;
while(p!=NULL) {
struct teacher *temp=p->next;
while(pre->next!=NULL&&cmp(pre->next,p))
pre=pre->next;
p->next=pre->next;
pre->next=p;
pre=dummyhead;
p=temp;
}
return dummyhead->next;
}
void save(struct teacher *head) {
head=sort(head);
FILE *file;
if((file=fopen("out.txt","w"))==NULL) {
printf("open error");
exit(0);
}
struct teacher *p=head;
while(p!=NULL) {
fprintf(file,"%d %s %d",p->num,p->name,p->year);
if(p->sex==0)
fprintf(file,"girl\n");
else
fprintf(file,"boy\n");
p=p->next;
}
fclose(file);
}