数据书上的算法实现....,其中那个从文本读出数据我用的时间最多,还习惯大侠多多指教.....
欢迎多指出错误...
//这个是用来练习编写排序的程序文档
//2011.10.4 juste0830
#include "base.h"
#include "founction.h"
main ()
{
SqList L1;
Input_List (&L1);
Output_List (&L1);
InsertSort(&L1);
printf ("排序后,");
Output_List (&L1);
printf ("\n\n\n\n\n");
}
/************* 文件名称:base.h ********************/
/********************************************************/
/* 文档名称:基础函数 */
/* 设 计 者:juste0830 */
/* 编写日期:2011.10.4 */
/* 作者练习方式:百度juste0830 */
/* 文档说明:为了考研练习的排序算法--数据结构 */
/********************************************************/
#include <stdio.h>
#define MAXSIZE 20
typedef int KeyType; //定义关键字的类型
typedef char* infoType; //定义信息类型
typedef struct {
KeyType key;
infoType otherinfo;
}RedType; //记录类型
typedef struct {
RedType r[MAXSIZE+1]; //r[0]闲置等
int length; //当前长度
}SqList; //俗称 顺序表
/********************************************************/
/* 函数名称:判断小于 */
/* 设 计 者:juste0830 */
/* 编写日期:2011.10.4 */
/* 函数说明:a要比较的一个参数,b为另一个参数 */
/* 属于小于关系返回1,否者返回0。 */
/********************************************************/
int LT(KeyType a,KeyType b) //比较函数,小于返回1
{
if (a<b)
return 1;
else
return 0;
}
/********************************************************/
/* 函数名称:获取数据 */
/* 设 计 者:juste0830 */
/* 编写日期:2011.10.4 */
/* 函数说明:通过文本输入数据,返回到顺序表L中 */
/* 获取数据成功了,返回0 。 */
/********************************************************/
int Input_List(SqList *L)
{
char name[30];
FILE *fp;
int i=1;
printf ("please input DataFile name:\n");
scanf ("%s",name);
fp=fopen (name,"r");
L->length=0;
while(!feof(fp)&&L->length<MAXSIZE+1)
{
fscanf(fp,"%d",&L->r[i].key);
L->length++;
i++;
}
return 0;
}
/********************************************************/
/* 函数名称:输出顺序表 */
/* 设 计 者:juste0830 */
/* 编写日期:2011.10.4 */
/* 函数说明:从从顺序表的第一个数据开始输出数据 */
/* 输出数据成功了,返回0。 */
/********************************************************/
int Output_List(SqList *L)
{
int i=1;
printf ("链表中的数据为:\n");
for (i=1;i<L->length+1;i++)
{
printf ("%4d",L->r[i].key);
}
printf ("\n");
return 0;
}
/**************文件名称:founction.h********************/
/********************************************************/
/* 函数名称:插入排序 */
/* 设 计 者:juste0830 */
/* 编写日期:2011.10.4 */
/********************************************************/
int InsertSort(SqList *L) { // 算法10.1
// 对顺序表L作直接插入排序。
int i,j;
for (i=2; i<=L->length; ++i)
if (LT(L->r[i].key, L->r[i-1].key)) {
// "<"时,需将L.r[i]插入有序子表
L->r[0] = L->r[i]; // 复制为哨兵
for (j=i-1; LT(L->r[0].key, L->r[j].key); --j) //意识到改颜色的地方的区别了嘛...
L->r[j+1] = L->r[j]; // 记录后移
L->r[j+1] = L->r[0]; // 插入到正确位置
}
return 0;
}