The title means: Merge two ordered arrays into the first array, so that the merged arrays are still ordered, and assume that the first array has enough space.
Problem-solving ideas: At the beginning of this topic, I am also desperate to start from the beginning, the result is very troublesome, always have one or two positions go wrong, the array is not as simple as a linked list to insert a node, we have to solve is the location of the insertion node problem. Fortunately, the internet looked at other people's practice, suddenly thought can be traversed from the back, because each array is ordered, compare the last position of the two array element size can determine the final position of the element, and finally use this idea ac this problem.
#include <stdio.h> #include <stdlib.h>void merge (int a[], int m, int b[], int n) { int i=0,j=0;while (m& &n) {if (a[m-1]>b[n-1]) {a[m+n-1]=a[m-1];m--;} else{a[m+n-1]=b[n-1];n--;}} while (n) {a[n-1]=b[n-1];n--;}} int main () {int m,n,i;while (scanf ("%d%d", &m,&n)!=eof) {int *a= (int *) malloc (sizeof (int) * (m+n)); int *b= (int *) malloc (sizeof (int) *n), for (i=0;i<m;i++) scanf ("%d", &a[i]), for (i=0;i<n;i++) scanf ("%d", &b[i]); for (i= m;i<m+n;i++) A[i]=0;merge (A,m,b,n), for (i=0;i<m+n;i++) printf ("%d", A[i]);p rintf ("\ n");} return 0;}
Leetcode 88th question-merge Sorted Array