插入排序(二)——二分法插入排序(稳定的排序)(非递归实现)

 
//文件bin_Sort.cpp
#include <stdio.h>
#include "table.h"void binarysort(table *tab)
{
 int i,j,left,right,mid;
 for(i=2;i<=tab->length ;i++)
 {
  tab->r[0].key =tab->r.key ;/*保存待插入的元素*/
  left=1;right=i-1;/*注意这里是将第i个元素插入到前面i-1个已排序的序列中,相当于在前面i-1中找插入位置*/
  while(left<=right)
  {
   mid=(left+right)/2;
   if(tab->r[0].key <tab->r[mid].key)/*if(tab->r.key <tab->r[mid].key)*/
   {
    right=mid-1;
   }
   else
   {
    left=mid+1;
   }
  }
  for(j=i-1;j>=left;j--)/*将前面i-1个已排序的序列腾出一个空间*/
  {
   tab->r[j+1].key=tab->r[j].key ;/*后移,空出插入位置*/
  }
  tab->r[left].key =tab->r[0].key ;/*插入第i个元素的副本*/
 }
}
void main()
 {
  int i; table tab;
 //tab.length=7;
 
 printf("please input the length of the table \\n");
 //printf("\\n");
 scanf("%d",&tab.length );
 tab.r[0].key=0; 
 /*tab.r[1].key=312;*/
 //getchar();//消除回车符 printf("please input the item of the table \\n");
 
 for (i=1;i<=tab.length;i++)
 {
  scanf("%d",&tab.r.key );
  
 }
  printf("the old order \\n");
  for (i=1;i<=tab.length;i++)
 {
  printf("%d\\t",tab.r.key );
  
 }
  
  printf("\\n the new order \\n"); 
 /*table t=*tab;*/
 binarysort(&tab); for (i=1;i<=tab.length;i++)
  {
   /*scanf("%d",&tab->r.key );*/
   printf("%d\\t",tab.r.key );
  }
 
 scanf("%d",&i);
 
 }
原文地址:https://www.cnblogs.com/zhiji6/p/1649302.html