点击(此处)折叠或打开
- #include<stdio.h>
- int
- binarysearch(int sou[],int length,int n){
- int low,high,mid;
- low = 0;
- high = length - 1;
- while (low <= high){
- mid = (low + high) / 2;
- if (sou[mid] < n)
- low = mid + 1;
- else
- high = mid - 1;
- }
- return high;
- }
- void
- mergeArray(int sou[],int des[],int m,int n){
- int temp;
- int place;
- int i,j;
- int flag = 1;
- for (i = 0;i < n;i++)
- {
- temp = des[i];
- if (flag){
- place = binarysearch(sou,m,temp);
- if (place != (m -1))
- {
- for (j = i - 1;j >= 0;j--)
- des[j+1] = des[j];
- des[0] = sou[m-1];
- for (j = m - 1;j > place;j--)
- sou[j] = sou[j-1];
- sou[place+1] = temp;
- }
- else
- {
- place = binarysearch(des,i,temp);
- if (place != i - 1)
- {
- for (j = i - 1;j > place;j--)
- des[j+1] = des[j];
- des[place+1] = temp;
- flag = 0;
- }
- else
- break;
- }
- }
- else
- {
- place = binarysearch(des,i,temp);
- if (place != i - 1)
- {
- for (j = i - 1;j > place;j--)
- des[j+1] = des[j];
- des[place+1] = temp;
- }
- else
- break;
- }
- }
- }
- int
- main(int argc,char* argv[])
- {
- int sou[] = {1,3,5,6,12,15,17,19};
- int des[] = {2,3,4,7,12,21};
- int i;
- int sou_len = sizeof(sou)/sizeof(sou[0]);
- int des_len = sizeof(des)/sizeof(des[0]);
- mergeArray(sou,des,sou_len,des_len);
- for (i = 0;i < sou_len;i++)
- printf("%d ",sou[i]);
- for (i = 0;i < des_len;i++)
- printf("%d ",des[i]);
- putchar('\n');
- return 0;
- }