For integer types, merge sort can be made inplace using some mathematics trick of modulus and division. That means storing two elements value at one index and can be extracted using modulus and division.
First we have to find a value greater than all the elements of the array. Now we can store the original value as modulus and the second value as division. Suppose we want to store arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value of arr[j]. So below is the implementation on merge sort.
divisor = maxele (absolute max element in the array)+1 (so that we always get non zero remainder) quotient = min(first, second) remainder = original element
Note: (when getting current element, assume the current container already has encoded element hence using % divisor) first = arr[i] % divisor second = arr[j] % divisor
encoded element = remainder + quotient*divisor
Possible issues in Merging:
1. If current number is Integer.MAX then new encoded value which is usually greater than current element will cause integer overflow and data corruption (In python there is no limit to number size so this issue will not occur).
2. Doesn’t handle negative numbers (ie, when encoding a -ve number(current) with another -ve number(chosen smallest) the sign can’t be preserved since both numbers have -ve sign. Also absolute values must be used when computing dividend = divisor*quotient+remainder (divisor = maxele, quotient = smallest, remainder = original) and sign must be restored, still it might not work due to sign preservation issue.
3. Only applicable to Unsigned integers, like indexes which are usually non-negative.
4. AUX = O(n) in worst case, assuming in a language like python where there is no limit to word/integer size, when input array elements are almost at Integer.MAX, then encoded value will require possibly 2x bits space to represent new number, the 2x bit space on whole can become +1x array size, which is almost like creating an AUX array but in an indirect way.
5. mod and division operations are the costliest, hence reduces overall performance(upto some extent).
// C++ program to sort an array using merge sort such
Please Login to comment...