Anon Anon - 3 months ago 9
C# Question

How do I redisplay an array after a mergesort algorithm so that each step is shown?

This is my mergesort method for sorting an array, it displays the sorted array fine, but how would I show each partially solved step?



public void mergeSort(string[] sortArray, int lower, int upper)
{
int middle;
if (upper == lower)
{
return;
}
else
{
middle = (lower + upper) / 2;
mergeSort(sortArray, lower, middle);
mergeSort(sortArray, middle + 1, upper);
Merge(sortArray, lower, middle + 1, upper);
}

}





I was thinking of adding

foreach (string a in sortArray)
{
txtOutput.Text += a + "\t";
}

To the end of the array, but then when I display the sorted method, all the partial solutions display together. Into something like

Sorted array:
1 8 7 3 1 7 3 8 1 3 7 8 1 3 7 8

I want to display it as

Partially sorted array:

1 8 7 3

1 7 3 8

1 3 7 8

Sorted array:

1 3 7 8

Answer

After the foreach loop append a newline('\n') to your output string.

if(lower == 0 && upper == sortArray.Length-1)
   output +="Sorted Array:\n"

foreach(var a in sortedArray)
{
//Display Logic
}