Note that there are some explanatory texts on larger screens.

plurals
  1. POmergesort - with an insignificant change throws SystemInvalidOperationException
    text
    copied!<p>A very strange thing occured in my program. Here is the simplified code.</p> <pre><code>class Program { static void Main(string[] args) { ArrayList numbers = new ArrayList(); numbers.Add(1); numbers.Add(3); numbers.Add(4); numbers.Add(2); var it = Sorts.MergeSort((ArrayList)numbers.Clone()); Sorts.PrintArray(it, "mergesort"); Console.WriteLine("DONE"); Console.ReadLine(); } } public static class Sorts { public static ArrayList BubbleSort(ArrayList numbers) { bool sorted = true; for (int i = 0; i &lt; numbers.Count; i++) { for (int j = 1; j &lt; numbers.Count; j++) { if ((int)numbers[j - 1] &gt; (int)numbers[j]) { int tmp = (int)numbers[j - 1]; numbers[j - 1] = numbers[j]; numbers[j] = tmp; sorted = false; } } if (sorted) { return numbers; } } return numbers; } public static ArrayList MergeSort(ArrayList numbers, int switchLimit = 3) { //if I use this if - everything works if (numbers.Count &lt;= 1) { // return numbers; } //the moment I use this condition - it throws SystemInvalidOperationException in function Merge in the line of a "for"-loop if (numbers.Count &lt;=switchLimit) { return Sorts.BubbleSort(numbers); } ArrayList ret = new ArrayList(); int middle = numbers.Count / 2; ArrayList L = numbers.GetRange(0, middle); ArrayList R = numbers.GetRange(middle, numbers.Count - middle); L = MergeSort(L); R = MergeSort(R); return Merge(L, R); } private static ArrayList Merge(ArrayList L, ArrayList R) { ArrayList ret = new ArrayList(); int l = 0; int r = 0; for (int i = 0; i &lt; L.Count + R.Count; i++) { if (l == L.Count) { ret.Add(R[r++]); } else if (r == R.Count) { ret.Add(L[l++]); } else if ((int)L[l] &lt; (int)R[r]) { ret.Add(L[l++]); } else { ret.Add(R[r++]); } } return ret; } //--------------------------------------------------------------------------------- public static void PrintArray(ArrayList arr, string txt = "", int sleep = 0) { Console.WriteLine("{1}({0}): ", arr.Count, txt); for (int i = 0; i &lt; arr.Count; i++) { Console.WriteLine(arr[i].ToString().PadLeft(10)); } Console.WriteLine(); System.Threading.Thread.Sleep(sleep); } } </code></pre> <p>There is a problem with my Sorts.MergeSort function. When I use it normally (take a look at the first if-condition in a function - all works perfectly. But the moment when I want it to switch to bubblesort with smaller input (the second if-condition in the function) it throws me an SystemInvalidOperationException. I have no idea where is the problem. Do you see it? Thanks. :) Remark: bubblesort itself works - so there shouldn't be a problem in that sort...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload