算法题:数组合并问题的解法

 描述:有两个有序数组A,B,内存A在A的末尾有足够多的空间容纳B,实现函数:把B中的所有数字插入到A中,并且保持A中的所有数字是排序的。

解法:

 1 #include<stdio.h> 
 2 #include<string.h>
 3 
 4 void newArray( char stringA[], char stringB[], int length){
 5     if(stringA == NULL && stringB == NULL && length < 0)
 6         return;
 7     
 8     int lengthA = 0;
 9     int lengthB = strlen(stringB);
10 
11     int i = 0;
12     
13     while(stringA[i] != ''){
14         ++lengthA;
15         ++i;
16     }
17         
18     int newLength = lengthA + lengthB;
19     if(newLength > length)
20         return;
21         
22     int indexofA = lengthA - 1;
23     int indexofB = lengthB - 1;
24     int indexNew = newLength - 1;
25 
26     while(indexofA >= 0 && indexofB >= 0){
27         if(stringA[indexofA] > stringB[indexofB]){
28             stringA[indexNew--] = stringA[indexofA];             
29             indexofA--;                                     //A数组的索引向前移动一位
30         }
31         else{
32             stringA[indexNew--] = stringB[indexofB];        
33             indexofB--;                                     //B数组的索引向前移动一位
34         }
35     }
36     
37 //    printf("%d %d
", indexofA, indexofB);
38     
39     if(indexofA >= 0){
40         return;
41     }
42     if(indexofB >= 0){                                      //将剩下的B数组中的内容拷贝到A中
43         while(indexofB >= 0){
44         stringA[indexNew--] = stringB[indexofB];
45         indexofB--;
46         }
47     }
48     stringA[newLength + 1] = '';
49     
50 }
51 
52 int main(){
53     char str1[20] = {6, 8, 20};
54     char str2[4] = { 1, 3, 4, 30};
55     newArray(str1, str2, 20);
56     int j = 0;
57     while(str1[j] != ''){
58         printf("%d  ", str1[j]);
59         j++;
60     }
61     return 0;
62 }

算法详解:

我们知道从头开始进行合并很难实现O(n)级别的算法。但是我们需要转变一下思想就可以实现。即从尾部开始扫描并进行合并。

我们需要先将两个数组中的元素个数求出来,并且相加得出需要将A数组从哪里开始赋值(假如计算结果是newlength),这样就可以从尾部对两个数组进行比较:将大的数字从newlength开始赋值一直到某一个数组结束(如果B数组到头了,那么算法结束;如果A数组结束而B没有,那么只需要将B数组剩下的数字一一复制到A中剩下的空间即可)。

原文地址:https://www.cnblogs.com/dormant/p/5259709.html