C-Sharp-Algorithms icon indicating copy to clipboard operation
C-Sharp-Algorithms copied to clipboard

Inefficient merge soft

Open davidich opened this issue 8 years ago • 3 comments

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?

davidich avatar Jun 24 '17 09:06 davidich

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.

aalhour avatar Jul 05 '17 20:07 aalhour

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?

davidich avatar Jul 05 '17 22:07 davidich

That is correct. Would you like to submit a PR for implementing this optimization?

aalhour avatar Aug 09 '17 15:08 aalhour