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