关于合并两个有序数组

1505阅读 0评论2012-10-21 lys5300
分类:LINUX

   使用一个空间来归并两个有序数组。


点击(此处)折叠或打开

  1. #include<stdio.h>


  2. int
  3. binarysearch(int sou[],int length,int n){
  4.     int low,high,mid;

  5.     low = 0;
  6.     high = length - 1;
  7.     while (low <= high){
  8.         mid = (low + high) / 2;
  9.         if (sou[mid] < n)
  10.             low = mid + 1;
  11.         else
  12.             high = mid - 1;
  13.     }
  14.     return high;
  15. }



  16. void
  17. mergeArray(int sou[],int des[],int m,int n){
  18.     int temp;
  19.     int place;
  20.     int i,j;
  21.     int flag = 1;

  22.     for (i = 0;i < n;i++)
  23.     {
  24.         temp = des[i];
  25.         if (flag){
  26.             place = binarysearch(sou,m,temp);
  27.             if (place != (m -1))
  28.             {
  29.                 for (j = i - 1;j >= 0;j--)
  30.                     des[j+1] = des[j];
  31.                 des[0] = sou[m-1];
  32.                 for (j = m - 1;j > place;j--)
  33.                     sou[j] = sou[j-1];
  34.                 sou[place+1] = temp;
  35.             }
  36.             else
  37.             {
  38.                 place = binarysearch(des,i,temp);
  39.                 if (place != i - 1)
  40.                 {
  41.                     for (j = i - 1;j > place;j--)
  42.                         des[j+1] = des[j];
  43.                     des[place+1] = temp;
  44.                     flag = 0;
  45.                 }
  46.                 else
  47.                     break;
  48.             }
  49.         }
  50.         else
  51.         {
  52.             place = binarysearch(des,i,temp);
  53.             if (place != i - 1)
  54.             {
  55.                 for (j = i - 1;j > place;j--)
  56.                     des[j+1] = des[j];
  57.                 des[place+1] = temp;
  58.             }
  59.             else
  60.                 break;
  61.         }
  62.     }
  63. }


  64. int
  65. main(int argc,char* argv[])
  66. {
  67.     int sou[] = {1,3,5,6,12,15,17,19};
  68.     int des[] = {2,3,4,7,12,21};
  69.     int i;

  70.     int sou_len = sizeof(sou)/sizeof(sou[0]);
  71.     int des_len = sizeof(des)/sizeof(des[0]);

  72.     mergeArray(sou,des,sou_len,des_len);

  73.     for (i = 0;i < sou_len;i++)
  74.         printf("%d ",sou[i]);
  75.     for (i = 0;i < des_len;i++)
  76.         printf("%d ",des[i]);
  77.     putchar('\n');
  78.     return 0;
  79. }


上一篇:尾递归优化快速排序
下一篇:tac命令