Is this parallel merge sort done correctly? It looks right, I took 40 seconds to write a test, and it did not work.
Its essence is that I need to sort by breaking the array in half each time. Then I tried to make sure that I was wrong, and asked a question about checking sanity (my own mind). I wanted to post the sort , but decided that it was difficult to complicate when viewing the answer, so I implemented below.
There is no point in creating a task / thread to sort a 4 byte array, but to study threads. Is there something wrong or something that I can change to make it better. It looks perfect to me, but I would like to get general feedback.
static void Main(string[] args) { var start = DateTime.Now; //for (int z = 0; z < 1000000; z++) int z = 0; while(true) { var curr = DateTime.Now; if (curr - start > TimeSpan.FromMinutes(1)) break; var arr = new byte[] { 5, 3, 1, 7, 8, 5, 3, 2, 6, 7, 9, 3, 2, 4, 2, 1 }; Sort(arr, 0, arr.Length, new byte[arr.Length]); //Console.Write(BitConverter.ToString(arr)); for (int i = 1; i < arr.Length; ++i) { if (arr[i] > arr[i]) { System.Diagnostics.Debug.Assert(false); throw new Exception("Sort was incorrect " + BitConverter.ToString(arr)); } } ++z; } Console.WriteLine("Tried {0} times with success", z); } static void Sort(byte[] arr, int leftPos, int rightPos, byte[] tempArr) { var len = rightPos - leftPos; if (len < 2) return; if (len == 2) { if (arr[leftPos] > arr[leftPos + 1]) { var t = arr[leftPos]; arr[leftPos] = arr[leftPos + 1]; arr[leftPos + 1] = t; } return; } var rStart = leftPos+len/2; var t1 = new Thread(delegate() { Sort(arr, leftPos, rStart, tempArr); }); var t2 = new Thread(delegate() { Sort(arr, rStart, rightPos, tempArr); }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); var l = leftPos; var r = rStart; var z = leftPos; while (l<rStart && r<rightPos) { if (arr[l] < arr[r]) { tempArr[z] = arr[l]; l++; } else { tempArr[z] = arr[r]; r++; } z++; } if (l < rStart) Array.Copy(arr, l, tempArr, z, rStart - l); else Array.Copy(arr, r, tempArr, z, rightPos - r); Array.Copy(tempArr, leftPos, arr, leftPos, rightPos - leftPos); }