静态查找表
1 顺序表的查找
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
typedef long KeyType;
#define key number
struct ElemType
{long number;char name[9];int politics;int chinese;int math;int English;int physics;int chemistry;int biology;int total;
};
struct StaticTable
{struct ElemType * elem;int length;
};
void visit(struct ElemType c)
{printf("% -8ld %8s%5d%5d%5d%5d%5d%5d%5d%5d\n", c.number, c.name, c.politics, c.chinese, c.math,c.English, c.physics, c.chemistry, c.biology, c.total);
}
void InputFromFile(FILE * f, struct ElemType * c)
{fscanf(f, "%ld%s%d%d%d%d%d%d%d", &c->number, c->name, &c->politics, &c->chinese, &c->math,&c->English, &c->physics, &c->chemistry, &c->biology);
}
void InputKey(KeyType * k)
{scanf("%ld", k);
}
//静态查找表(顺序表)基本操作
//1 由数据文件构造静态顺序查找表
void create_SeqFormFile(struct StaticTable * St, char * filename)
{int i;FILE * f;f = fopen(filename, "r");fscanf(f, "%d", &St->length);St->elem = (struct ElemType * ) calloc(St->length + 1, sizeof (struct ElemType));if (!St->elem)exit(-1);for(i = 1; i <= St->length; i++){InputFromFile(f, &St->elem[i]);}fclose(f);
}
//2 重建静态查找表为按关键字非降序排列
void Ascend(struct StaticTable * St)
{int i, j, k;for (i = 1; i < St->length; i++){k = i;St->elem[0] = St->elem[i];for (j = i + 1; j <= St->length; j++){if (St->elem[j].key < St->elem[0].key){k = j;St->elem[0] = St->elem[j];}}if (k != i){St->elem[k] = St->elem[i];St->elem[i] = St->elem[0];}}
}
//3 组合(构建+排序)
void create_ordFormFile(struct StaticTable * St, char * filename)
{create_SeqFormFile(St, filename);Ascend(St);
}//4 查找
int search_Seq(struct StaticTable St, KeyType key)
{int i;St.elem[0].key = key;for (i = St.length; St.elem[i].key != key; --i){}return i;
}//5 折半查找
int search_bin(struct StaticTable St, KeyType key)
{int mid;int low = 1;int high = St.length;while (low <= high){mid = (low + high) / 2;if (key == St.elem[mid].key)return mid;else if (key < St.elem[mid].key)high = mid - 1;elselow = mid + 1;}return 0;
}
//6 遍历输出
void Traverse(struct StaticTable St, void (* visit)(struct ElemType))
{int i;struct ElemType * p = ++St.elem;for (i = 1; i <= St.length; i++){visit(*p++);}
}
//7 销毁
bool destroy(struct StaticTable * St)
{free(St->elem);St->elem = NULL;St->length = 0;return true;
}int main() {struct StaticTable St;int i;long s;char filename[13];printf("Enter file name: \n");scanf("%s", filename);create_SeqFormFile(&St, filename);for (i = 1; i <= St.length; i++){St.elem[i].total = St.elem[i].politics + St.elem[i].chinese + St.elem[i].English+ St.elem[i].math + St.elem[i].physics + St.elem[i].chemistry + St.elem[i].biology;}Traverse(St, visit);printf("Enter id whose searched:");InputKey(&s);i = search_Seq(St, s);if (i)visit(St.elem[i]);elseprintf("Not found!");destroy(&St);return 0;
}
数据文件
5
179328 何芳 85 89 98 100 93 80 47
179325 陈红 85 86 88 100 92 90 45
179326 路华 78 75 90 80 95 88 37
179327 张三 82 90 78 98 84 96 40
179324 李四 76 85 94 57 77 69 44