What in place sort when two arrays are in order?

好久不见. 提交于 2019-12-12 09:56:03

问题


I am working on this question. My function prototype is

static void Sort(byte[] arr, int leftPos, int rightPos)

In the 2nd part of the function i know leftPos to leftPos + (rightPos-leftPos)/2 and (rightPos-leftPos)/2 to rightPos are sorted in order.

I tried thinking of how i could do an in place sort knowing the two parts are in order. I couldnt think of any. I looked at the merge function on merge sort but it uses an output array rather than in place.

How do i sort it in place knowing both slices are in order?

Note: I was thinking i could pass in a extra array that is the same length as the main array to use as temp memory but the way i thought of would require me to do Array.Copy after each merge.


回答1:


In-place merge is possible, but it's complicated and doesn't give much performance gain. Below is some sample code from here. from is your leftPos, to is your rightPos, pivot is your (rightPos-leftPos)/2 and the lengths are the lengths of each half.

void merge(int from, int pivot, int to, int len1, int len2) {
  if (len1 == 0 || len2==0) return;
  if (len1+len2 == 2) {
   if (compare(pivot, from) < 0)
    exchange(pivot, from);
   return;
  }
  int first_cut, second_cut;
  int len11, len22;
  if (len1 > len2) {
   len11=len1/2;
   first_cut = from + len11;
   second_cut = lower(pivot, to, first_cut);
   len22 = second_cut - pivot;
  } else {
   len22 = len2/2;
   second_cut = pivot + len22;
   first_cut = upper(from, pivot, second_cut);
   len11=first_cut - from;
  }
  rotate(first_cut, pivot, second_cut);
  int new_mid=first_cut+len22;
  merge(from, first_cut, new_mid, len11, len22);
  merge(new_mid, second_cut, to, len1 - len11, len2 - len22);
}


来源:https://stackoverflow.com/questions/4674994/what-in-place-sort-when-two-arrays-are-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!