how to use memmove in insertion sort
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
3 Dec 06, 7:03PM
I believe the following piece of code is a good replacement using the "memmove" function.
#include <string.h> template <class T> 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; while (--j && temp < a[j - 1]); memmove(a + j + 1, a + j, (i - j)*sizeof(T)); a[j] = temp; } }
So an example of how to use this function could be:
#include <string.h> #include <stdio.h> template <class T> 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; while (--j && temp < a[j - 1]); memmove(a + j + 1, a + j, (i - j)*sizeof(T)); a[j] = temp; } } int main() { int a[6] = {100, 0, 1, -5, -10, -4}; insertionSort<int>(a, 6); for (int i = 0; i < 6; i++) printf("%d ", a[i]); printf("\n\n"); return 0; }
I hope this helps.
Login