Skip to main content
2 of 2
Fixing a bug in the algorithm - need to compare to correct element in right array

Just focussing on your Merge method here, since I felt like using it to merge 2 Lists of objects I had, you should note that using RemoveAtis really horrible performance wise. Especially at index 0. What the list has to do in that case is move the index of every object behind that one, down by 1. This is needless and will cause your method to be really slow for big collections (easily noticable when merging 2 lists of 10 000 items or more).

Just use indices on both list and iterate through them like you would with a for loop, instead of removing each item you covered from the list:

private static List<Node> Merge(List<Node> Left, List<Node> Right)
{
    List<Node> Result = new List<Node>();
    int leftIndex = 0;
    int rightIndex = 0;
    while (Left.Count > leftIndex && Right.Count > rightIndex )
    {
        if (Left[leftIndex].F < Right[rightIndex].F)
        {
            Result.Add(Left[leftIndex]);
            leftIndex++;
        }
        else
        {
            Result.Add(Right[rightIndex]);
            rightIndex++;
        }
    }

    while (Left.Count > leftIndex)
    {
        Result.Add(Left[leftIndex]);
        leftIndex++;
    }

    while (Right.Count > rightIndex)
    {
        Result.Add(Right[rightIndex]);
        rightIndex++;
    }

    return Result;
}