Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
There are 2 sorted arrays of size m and m+n, respectively.
First array (of size m) has m elements and the Second array (of size m+n) has only n elements (last m positions are blank).
So, the total number of elements in both the arrays is m+n (m in the first and n in the second). Write code to merge the m+n elements in the 2nd array such that the result is sorted. If the two arrays are as below:
Then the output should be:
Algorithm: 1. Let a, b & c be three pointers.
If (arr1[a] > arr2[b])
arr2[c] = arr1[a]
a--
else
arr2[c] = arr2[b]
b--
c--
3. If a >=0
Move remaining elements from arr1 to arr2 starting from a in arr1 to position c in arr2 in backward fashion
Code:
/** size of array arr2 should be m+n (and not n) */
void mergeIntoSecond(int * arr1, int m, int*arr2, int n)
{
int a=m-1, b=n-1, c=m+n-1;
while(a>=0 && b>=0)
{
if(arr1[a] > arr2[b])
{
arr2[c] = arr1[a];
a--;
}
else
{
arr2[c] = arr2[b];
b--;
}
c--;
}
for(;a>=0;a--, c--)
arr2[c] = arr1[a];
}
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment