插入排序(四)——表插入排序(稳定排序)

//头文件table_Link.h
#include <stdio.h>
#define MAXSIZE 100  /*文件中记录个数的最大值*/
typedef int keytype;  /*定义排序码类型为整型*/
typedef struct{
 keytype key;
 int link;
     /*此处还可以定义记录中除排序码外的其他域*/
}recordtype;        /*记录类型的定义*/

typedef struct{ recordtype r[MAXSIZE+1];
 int length;  /*待排序文件中记录的个数*/
}table_link;        /*待排序文件类型*/
 
 
 
//表插入排序文件table_InsertSort.cpp
#include <stdio.h>
#include "table_Link.h"void tableinsertsort(table_link *tab)
{
 int i,p,q;
 tab->r[0].link=1; tab->r[1].link=0;/* 第一个元素先初始为有序静态表*/
 for(i=2;i<=tab->length;i++)/*依次从第2个元素开始,将所有元素插入有序表中,通过修改link实现*/
  {
   
   p=tab->r[0].link ;  /*p用来指向静态表的link,用于记录比较时候的当前位置*/
   q=0;  /*q用于记录比较当中前一位置*/
   while(p!=0&&tab->r.key>=tab->r[p].key)/*从前往后找位置,0的位置为静态表起始位置,>=有“=”则是稳定排序*/
   {
    q=p; /*相当于将与i同一组的,将i的位置空出来,以便往后移,来找i的位置*/
    p=tab->r[p].link ;/*继续向后查找 位置*/
   }
   tab->r.link =p; tab->r[q].link =i; /* 将第i个元素插入到q和p所指向的元素之间 */
  }
}
 
void main()
 {
  int i; table_link tab;
 //tab.length=7;
 
 printf("please input the length of the table \\n");
 //printf("\\n");
 scanf("%d",&tab.length );
 tab.r[0].key=0;  //getchar();//消除回车符
 printf("please input the  item of the table \\n");
 
 for (i=1;i<=tab.length;i++)
 {
  printf("please input the key of item of the table \\n");
  scanf("%d",&tab.r.key );
  printf("please input the link of item of the table \\n");
  scanf("%d",&tab.r.link );
 }
  printf("the old order \\n");
  for (i=1;i<=tab.length;i++)
 {
  printf("key:%d\\t|link:%d \\t",tab.r.key,tab.r.link );
  
 }
  
  printf("\\n the new order \\n"); 
 
 tableinsertsort(&tab); //for (i=0;i<=tab.length;i++)
 int link=tab.r[0].link ;
 while(link>0)
 {
  printf("%d\\t",tab.r[link].key );
  link=tab.r[link].link ;
 }
 
 scanf("%d",&i);
 
 }
原文地址:https://www.cnblogs.com/zhiji6/p/1649300.html