I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » C/C++ »

how to use memmove in insertion sort

andripatri\′s Photo
30 Nov 06, 10:32PM
(1 reply)
how to use memmove in insertion sort
I have this code: void insertionSort(T* a, int size) { for (int i = 1; i < size; i++) if (a[i] < a[i - 1]) { T temp = a[i]; int j = i; do { a[j] = a[j - 1]; --j; } while (j > 0 && temp < a[j - 1]); a[j] = temp; } }

and I need to make a change using memmove to shift values in a single call per outer loop cycle rather than performing multiple assignments in its inner loop.

Does anybody has an idea of how can this be accomplish? I have been trying and it doesn't work for me. Thanks
lucian\′s Photo
3 Dec 06, 7:03PM
I believe the following piece of code is a good replacement using the "memmove" function.

#include &lt;string.h&gt;
 
template &lt;class T&gt;
void insertionSort&#40;T* a, int size&#41;
&#123;
  for &#40;int i = 1; i &lt; size; i++&#41;
    if &#40;a&#91;i&#93; &lt; a&#91;i - 1&#93;&#41;
    &#123;
      T temp = a&#91;i&#93;;
      int j = i;
      while &#40;--j &amp;&amp; temp &lt; a&#91;j - 1&#93;&#41;;
      memmove&#40;a + j + 1, a + j, &#40;i - j&#41;*sizeof&#40;T&#41;&#41;;
      a&#91;j&#93; = temp;
    &#125;
&#125;

So an example of how to use this function could be:

#include &lt;string.h&gt;
#include &lt;stdio.h&gt;
 
template &lt;class T&gt;
void insertionSort&#40;T* a, int size&#41;
&#123;
  for &#40;int i = 1; i &lt; size; i++&#41;
    if &#40;a&#91;i&#93; &lt; a&#91;i - 1&#93;&#41;
    &#123;
      T temp = a&#91;i&#93;;
      int j = i;
      while &#40;--j &amp;&amp; temp &lt; a&#91;j - 1&#93;&#41;;
      memmove&#40;a + j + 1, a + j, &#40;i - j&#41;*sizeof&#40;T&#41;&#41;;
      a&#91;j&#93; = temp;
    &#125;
&#125;
 
int main&#40;&#41;
&#123;
  int a&#91;6&#93; = &#123;100, 0, 1, -5, -10, -4&#125;;
 
  insertionSort&lt;int&gt;&#40;a, 6&#41;;
  for &#40;int i = 0; i &lt; 6; i++&#41;
    printf&#40;&quot;%d &quot;, a&#91;i&#93;&#41;;
  printf&#40;&quot;\n\n&quot;&#41;;
 
  return 0;
&#125;

I hope this helps.

Currently you need to be logged in to leave a message.