Skip to main content
deleted 9 characters in body; edited title
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

merge Merge sort C# time and space effciecencyefficiency

Please comment on time and space efficiency.

Please comment on time and space efficiency. thanks

merge sort C# time and space effciecency

Please comment on time and space efficiency. thanks

Merge sort C# time and space efficiency

Please comment on time and space efficiency.

edited tags
Link
Peilonrayz
  • 43.5k
  • 7
  • 76
  • 155
Source Link
Gilad
  • 5.3k
  • 5
  • 37
  • 63

merge sort C# time and space effciecency

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{
    [TestClass]
    public class MergeSortUnitTest
    {
        [TestMethod]
        public void MergeTest()
        {
            int[] array = new int[] { 5, 10, 1, 4, 2, 3, 7 };
            SortHalf(array, 0, array.Length-1); 

            int[] expectedOutput = new[] { 1, 2, 3, 4, 5, 7, 10 };
            CollectionAssert.AreEqual(expectedOutput, array);
        }
        private void SortHalf(int[] array, int startIndex, int endIndex)
        {
            int mid;
            if (endIndex > startIndex)
            {
                mid = (endIndex + startIndex) / 2;
                SortHalf(array, startIndex, mid);
                SortHalf(array, mid + 1, endIndex);
                DoMerge(array, startIndex,mid+1, endIndex);
            }
        }

        private void DoMerge(int[] array, int startIndex, int mid, int endIndex)
        {
            int[] temp = new int[array.Length];
            int i, start, numOfElements, position;
            start = mid - 1;
            position = startIndex;
            numOfElements = endIndex - startIndex + 1;
            while((startIndex <= start)&& (mid <= endIndex))
            {
                if(array[startIndex] <= array[mid])
                {
                    temp[position++] = array[startIndex++];
                }
                else
                {
                    temp[position++] = array[mid++];
                }
            }
            while(startIndex <= start)
            {
                temp[position++] = array[startIndex++];
            }

            while(mid <= endIndex)
            {
                temp[position++] = array[mid++];
            }

            for (i = 0; i < numOfElements; i++)
            {
                array[endIndex] = temp[endIndex];
                endIndex--;
            }

        }
    }
}

Please comment on time and space efficiency. thanks