Merge Sorted Array [LeetCode]

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Summary: It's easy, but should be careful about corner cases, like m is 0, n is 0. 

 1     void merge(int A[], int m, int B[], int n) {

 2         if(n == 0)

 3             return;

 4         if(m == 0) {

 5             memcpy(A, B, n * sizeof(B[0]));

 6             return;

 7         }

 8         int a = 0;

 9         int b = 0;

10         int a_idx = 0;

11         int new_len = m;

12         while(true) {

13             if(A[a] >= B[b]) {

14                 //insert B[b] before A[a]

15                 for(int i = new_len; i >= a + 1; i --) 

16                     A[i] = A[i - 1];

17                 A[a] = B[b];

18                 new_len ++;

19                 b ++;

20                 if(b >= n)

21                     break;

22                 a ++;

23             }else {

24                 if(a_idx >= m) {

25                     //copy rest B to tail of A

26                     memcpy(A + a, B + b, (n-b)*sizeof(A[0]));

27                     break;

28                 }

29                 a ++;

30                 a_idx ++;

31             }

32         }

33     }

 

你可能感兴趣的:(LeetCode)