Define a function
int * shuffle (int * p1, int length1, int * p2, int length2)
that "shuffles" the arrays where the first array has base address p1 with length len1
and the second array has base address p2 with length len2.
The function should return a dynamically allocated array containing all the shuffled elements .
To shuffle, we start with element zero of p1, followed by element zero of p2, followed by element one of p1 and so on
until the elements of (at least) one of the arrays are exhausted.
If there are still elements remaining to process from the other array , then we just tack them on at the end.
You must use pointer notation throughout the function (no square brackets).
Sample driver below.
#include <iostream>
using namespace std;
void print(int * nums, int length);
int * shuffle (int * p1, int length1, int * p2, int length2) ;
int main() {
int len1, len2;
cin >> len1 >> len2;
int nums1[] = {1,3,9,13,17};
int nums2[] = {4,6,14,18,20};
int * temp = shuffle(nums1,len1,nums2,len2) ;
print(temp, len1 + len2) ;
delete [] temp;
return 0;
}
void print(int * nums, int length) {
for (int i = 0; i < length;i++)
cout << *(nums + i) << " ";
cout << endl;
}
correct the code..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int *shuffle(int *p1, int length1, int *p2, int length2)
{
int *p = new int(length1+length2);
int *temp = p;
for(int i = 0, j = 0; i < length1 && j < length2;)
{
if(*(p1+i) < *(p2+j))
{
*temp++ = *(p1+i);
i++;
}
else
{
*temp++ = *(p2+j);
j++;
}
}
return p;
}
|