C-Sharp-Algorithms
C-Sharp-Algorithms copied to clipboard
Inefficient merge soft
int midIndex = collection.Count / 2;
var leftCollection = collection.GetRange(startIndex, midIndex);
var rightCollection = collection.GetRange(midIndex, (endIndex - midIndex) + 1);
leftCollection = InternalMergeSort<T>(leftCollection, 0, leftCollection.Count - 1, comparer);
rightCollection = InternalMergeSort<T>(rightCollection, 0, rightCollection.Count - 1, comparer);
No need to invoke GetRange, as it copies the data and consumes extra memory. Passing StartIndex, EndIndex along with the original array should be sufficient. Don't you think so?
Hey @davidich,
I am not sure about its inefficiency, the List<T>.GetRange(Int32, Int32) creates a shallow copy of the elements of the given list instance, not a deep copy. Shallow copies are more or less cheap references to the same data objects in memory, please refer to its documentation on this MSDN Page.
If you were referring to something else, then please elaborate.
I agree, it does shallow copy in case of reverence types. But for structs, even shallow copy will mean coping of entire structure. And if we disregard the struct case, I still don't see any point in memory waste for shallow copy of references. Modification to solve that issue is very simple, don't you think so?
That is correct. Would you like to submit a PR for implementing this optimization?