shuffle

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;
}
fuck pointers
You must use pointer notation throughout the function (no square brackets).


I want to slap your teacher in the face. This is a horrible, horrible sentence.

int *p = new int(length1+length2);

Here, you are not using array new. Instead you are just using normal new. You are not allocating length1+lenght2 ints. Instead, you are allocating a SINGLE int and constructing it with a value equal to length1+length2.

IE... that line does the same thing as this:
1
2
int* p = new int;
*p = length1+length2;



If you want array new, you want to use square brackets:

 
int* p = new int[ size ];
Topic archived. No new replies allowed.