The task is to implement the merge sorting algorithm, having read the implementation options on other sites and the wiki version, the implementation seemed rather cumbersome and not quite elegant, in my own version I set myself the task:
- Execute recursively.
- One function.
- Reduce the number of operands.
- Reduce the number of parameters to the pointer to the array passed to the function and the size of the array itself.
After some transformations, I reduced the code to the one below, compiled with the error "stuck overflow: access to a prohibited memory location," or "access violation during reading at the address ..".
I can’t find a leak for a long time and ask someone to notice more carefully and tell me where exactly the output goes beyond the array in this code:
void merge_sort(int* unsorted, unsigned int size) { if (size < 2) return; unsigned int middle = size >> 1; merge_sort(unsorted, middle); merge_sort(unsorted + middle, size - middle); int* first = unsorted; int* second = unsorted + middle; int* sorted = new int[size]; while (first != (unsorted + middle) && second != (unsorted + size)) *sorted++ = *first < *second ? *first++ : *second++; while (first != (unsorted + middle)) *sorted++ = *first++; while (second != (unsorted + size)) *sorted++ = *second++; sorted -= size; while (unsorted != second) *unsorted++ = *sorted++; delete[] sorted; } - At the moment: by finding the values ​​in the log, I found the function works correctly until the last cycle, which for some unknown reason becomes infinite ..
- Fully working version. After just something ..
size >> 1, but not normal humansize / 2? Where did the shift come from? - AnTsize >> 1<=>size / 2^1, which is essentially faster and there is no implicit type conversion double to int in the case ofsize / 2- PostPunkTheSmithunsigned intthese options are absolutely strictly equivalent. Never in C / C ++ code does it make sense to manually “optimize” integer division or multiplication by a compile-time constant. And to “optimize” the division by 2 is a gross profanity. Secondly, what else is "double to int" ??? Where did you see double ??? - AnT