Note that there are some explanatory texts on larger screens.

plurals
  1. POArray movement from a1,..,an,b1,..,bn to a1,b1,..,an,bn
    primarykey
    data
    text
    <p>Today, I met a question which is really puzzled me</p> <p><strong>Question</strong></p> <p>I have array just like:<code>arr[a1, a2, a3....an, b1, b2, b3.....bn]</code>, how to move the elements of the array to transfer it into <code>arr[a1, b1, a2, b2......an,bn]</code>, And you should do the movement in-place(<code>space complexity should be constant</code>).</p> <p>I tried my best to think it over and get an ugly algorithm just like bubble-sort:</p> <pre><code>b1 moves forward by n - 1; b2 moves forward by n - 2; . . bn-1 moves forward by 1; </code></pre> <p>But the time complexity is O(n<sup>2</sup>), who can give me a better algorithm? I find another better method just like quick-Sort:</p> <pre><code>First we swap the element from a(n/2) to a(n) with the elements from b1 to b(n/2);now we get two independent sub problems,So we can solve it by recursion. T(n) = 2T(n/2) + O(n) the time complexity is O(nlgn) </code></pre> <p>here are whole codes:</p> <pre><code>void swapArray(int *arr, int left, int right) { int mid = (left + right) &gt;&gt; 1; int temp = mid + 1; while(left &lt;= mid) { swap(arr[left++], arr[temp++]); } } void arrayMove(int *arr, int lb, int le, int rb, int re) { if(le - lb &lt;= 0 || re - rb &lt;= 0) return; int mid = (lb + le + 1) &gt;&gt; 1; int len = le - mid; if(rb + len &gt;= re) { swapArray(arr, mid + 1, rb); } else { swapArray(arr, mid, rb + len); } arrayMove(arr, lb, mid - 1, mid, le); arrayMove(arr, rb, rb + len, rb + 1 + len, re); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload