There is a major bug in your memory allocation. stackp
is an automatic (stack) array, which means its lifetime ends as soon as insert returns. You have to use another allocation method. You can have the caller allocate a new array and pass in both pointers, or you can do it yourself with malloc
(don't forget to free).
However, the rest looks all right. That's pretty much the only algorithm for a non in-place insert. You may be able to do it a bit faster with special tricks (e.g. copying two ints at once). memmove
and memcopy
may use such optimizations on some architectures.
Also, many algorithms would write stackp[index]
when the position is found, rather than at the end. But the core algorithm is basically the same.
An alternative would be to do the insert in-place (shifting only elements after the insert position), rather than using a new array. You would often expand with realloc
. This would be preferred in many situations as it saves copying time and avoids malloc
ing a new memory location (which may also fragment the heap).
Finally, an alternative data structure entirely is a linked list. This totally eliminates the need for copying elements, but uses more memory and prevents random access.