高级语言讲义2023计专(仅高级语言部分)

本文介绍了如何用C语言编写递归函数实现二分查找算法,并展示了如何构建存储教师信息的单链表,以及按照入职年份和教工号对链表进行排序并将结果保存至文件的过程。
摘要由CSDN通过智能技术生成

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);
}
  • 25
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值