一个插入排序算法

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 liye20000 的 blog

写这个算法的初衷是利用二分法排序为原型,借鉴c++的泛型的概念,写一个适合不同数据结构,适用于数组和指针的插入和排序一体的程序,但是时间和经理有限,经验也差很多,最近又有其他工作,只好把已经完成的部分贴出来,希望大家能够指正和完善,多多提出宝贵建议,谢谢。

//插入排序函数,v0.0
#include "stdafx.h"
//定义不同的数据结构,用户也可以自己定义
typedef int datatype;
//比较函数
int comparedate(datatype src, datatype des)
{
 if(src>des)
  return 1;
 else if(src<des)
  return -1;
 else
  return 0;
}
//排序函数
bool  cenfind(datatype tempnode, datatype *thead, long &from , long &to,long &mid,int(*fn)(datatype ,datatype))
{
  int i = 0;          
        datatype tcen = null;
  mid = (from + to)/2;
        tcen = thead[mid];   
        i = fn(tempnode ,tcen );    
        if(i>0)
        {
                from = mid + 1;
                if( (mid ==  from)||(mid == to))
     return false;
    cenfind(tempnode,thead,from,to,mid,fn);
        }
        else if(i == 0)
        {
                return true;
        }
        else
        {
                to = mid - 1;
                if( (mid ==  from)||(mid == to))
                        return false;
                cenfind(tempnode,thead,from,to,mid,fn);
        }
}
int main(int argc, char* argv[])
{
 datatype wholedate[10] ;
 datatype *thead = null;
 thead = &wholedate[0];
 int i;
 for(i = 0;i<10;i++)
 {
  wholedate[i]=-1;
 }
 datatype temp;
 long from,to,mid;
 long length=0;
 for(i = 0;i<8;i++)
 {
  from = 0;
  to = length;
  mid = 0;
 
  printf("datatype=");
  scanf("%d",&temp);
  if(length==0)
  {
    wholedate[length] = temp;
    length++;
  }
  else
  {
   if(cenfind(temp, thead, from , to,mid,comparedate))
   {

   }
   else
   {
     if(mid == length)
     {
      //add
      /*for(int t = length; t>=to; t--)
      {
       wholedate[t+1] = wholedate[t];
      }
      wholedate[to] = temp;*/
      wholedate[length] = temp;
      
     }
     else
     {
      //insert
      for(int t = length; t>=to+1; t--)
      {
       wholedate[t+1] = wholedate[t];
      }
      wholedate[to+1] = temp;
     }     
     length++;

   }    
  }
 }
 for(i = 0;i<10;i++)
 {
  printf("wholedate[%d] = %d\n",i,wholedate[i]);
 }
 printf("hello world!\n");
 return 0;
}

本文关键:一个插入排序算法
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top