c++ - How to use a stack of pointers to arrays, and access two arrays in the same command? -


just clear, homework assignment. i'm not asking me, i'm stuck on small portion of it.

i'm asked implement mergesort, each new array make has placed in stack of pointers. in code below, i'm trying split array recursively, merge them together. stack named ptrs. merge() function takes 2 sorted arrays , sizes.

template <typename t> t* mergesort<t>::mergesort(t arr[], int size) {      int size1 = (int)size/2;     int size2 = size - size1;      //i'll have base case cover arrays of size 1 or 2      ptrs.push(new t[size1]);     for(int = 0; < size1; i++) {         ptrs.top()[i] = arr[i];     }      ptrs.push(new t[size2]);     for(int = 0; < size2; i++) {         ptrs.top()[i] = arr[i + size1];     }      return merge(mergesort(todo, size1), mergesort(ptrs.top(), size2), size1, size2); 

my problem marked todo. how can access first array, if second 1 on top of stack?

why need stack @ all? since allocate 2 new arrays , copy 2 portions of input array, can recurse on them directly:

t* left = new t[size1]; for(int = 0; < size1; i++) //...  t* right = new t[size2]; for(int = 0; < size2; i++) /...  t* left_sorted  = mergesort(left,  size1); t* right_sorted = mergesort(right, size2); 

then merge, being careful deallocate:

delete[] left; delete[] right;  t* merged = merge(left_sorted, right_sorted, size1, size2);  delete[] left_sorted; delete[] right_sorted;  return merged; 

if allowed assignment, recommend using std::vector instead of plain arrays + sizes. consider in-place merge avoid allocations.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -