怎样合并排序数组(How to merge 2 sorted arrays?)
Question: We have 2 sorted arrays and we want to combine them into a single sorted array.
Input: arr1[] = 1, 4, 6, 8, 13, 25 || arr2[] = 2, 7, 10, 11, 19, 50
Output: 1, 2, 4, 6, 7, 8, 10, 11, 13, 19, 50
最简单的方法之一就是把两个数组复制到一个新的数组中,对这个新的数组进行排序。但这样就不能利用原来的两个数组已经排好序这个条件了。
我们需要一个不一样的方法。下面是可行方法之一:
- 为两个数组初始化两个变量作为索引。
- 假设i指向arr1[],j指向arr2[]。
- 比较arr1[i],arr2[j],哪个小就将那个复制进新的数组,并增加相应的系数。
- 重复上述步骤直到i和j都到达数组尾部。
相应的算法实现:
#include<stdio.h> //a function to merge two arrays //array1 is of size 'l' //array2 is of size 'm' //array3 is of size n=l+m void merge(int arr1[], int arr2[], int arr3[], int l, int m, int n) { //3 counters to point at indexes of 3 arrays int i,j,k; i=j=k=0; //loop until the array 1 and array 2 are within bounds while(i<l && j<m) { //find the smaller element among the two //and increase the counter if(arr1[i] < arr2[j]) { arr3[k] = arr1[i]; //increment counter of 1st array i++; } else { arr3[k] = arr2[j]; //increment counter of second array j++; } //increase the counter of the final array k++; } //now fill the remaining elements as it is since they are //already sorted while(i<l) { arr3[k] = arr1[i]; i++; k++; } while(j<m) { arr3[k] = arr2[j]; j++; k++; } } //driver program to test the above function int main(void) { int arr1[5] = {1, 5, 9, 11, 15}; int arr2[5] = {2, 4, 13, 99, 100}; int arr3[10] = {0}; merge(arr1, arr2, arr3, 5, 5, 10); int i=0; for(i=0;i<10;i++) printf("%d ",arr3[i]); return 0; }
Copyright © 2015 programnote