I am implementing a version of merge sort in c. For the first step I have to split the array into sub-arrays.
Is it bad practice to simply do this by having two pointers, one pointing to the start of the original array and the second pointing to the middle?
Or should I malloc 2 new memory slots, copy the appropriate values here and then keep a pointer to this space?
I don't think it's bad practice if you know what you're doing. In some cases, you sacrifice readability for efficiency. It's probably more clear if you'd just create two more arrays, but if you have a firm grasp on arrays and pointers, why allocate extra memory?
Absolutely not! The whole point of programming in C is being able to do these neat pointer tricks!
Do note, however, that mergesort is not inplace so you will still need to malloc an auxiliary array. If you do the correct pointer tricks you can just malloc once and reuse it though.
It's just fine to use one array in such case (as merge sort). Calling malloc is unnecessary, unless the size of the array is too big for the stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With