二分查找的变形 二分插入

int update_glist(struct gdev_info *ginfo, int sum_num)
{
  int pre, mid, tai, ret;
  pre = 0; 
  tai = sum_num - 1;
	
  if(0 == sum_num)
  {
    insert_glist(ginfo, 0, 0); 
    return 1;
  }
	
  struct gdev_info *tmp_info;
  while(pre <= tai)//等号的作用,在于循环结束时pre的位置即为要插入的位置(tail >= 0时)
  {
    //mid = (pre + tai)/2;
    mid = pre + (tai - pre)>>2;//防止溢出
    tmp_info = &g_infolist[mid];
    ret = memcmp(ginfo->mac + 6, tmp_info->mac + 6, 6); 
    if(ret < 0)
    {   
      tai = mid - 1;
    }   
    else if(ret > 0)
    {   
      pre = mid + 1;//maybe do'not need to add 1
    }   
    else
    {   
      //成功找到
      return 0;
    }   
    //printf("mid:%d\n",mid);
  
  }
  if(G_INFO_MAX_NUM == sum_num )
  {
    return -1; 
  }
  ret = insert_glist(ginfo, pre, sum_num);
  return (ret);
	
}


你可能感兴趣的:(二分查找的变形 二分插入)