// ------------------------------------------------------- // delegates used in this class public MyContainer <T> Merge(CompareDelegate cmp, MyContainer <T> other) { var i = 0; var j = 0; var finished = false; var res = new MyContainer <T>(); while (!finished) { if (cmp(_items[i], other._items[j]) > 0) { res.Add(other._items[j]); j++; } else { res.Add(_items[i]); i++; } finished = i >= Count || j >= other.Count; } for (var k = i; k < Count; k++) { res.Add(_items[k]); } for (var k = j; k < other.Count; k++) { res.Add(other._items[k]); } return(res); }
public MyContainer <T> MergeFromTo(CompareDelegate cmp, int from, int mid, int to) { var i = from; var j = mid; var finished = false; var res = new MyContainer <T>(); while (!finished) { if (cmp(_items[i], _items[j]) > 0) { res.Add(_items[j]); j++; } else { res.Add(_items[i]); i++; } finished = i >= mid || j >= to; } for (var k = i; k < mid; k++) { res.Add(_items[k]); } for (var k = j; k < to; k++) { res.Add(_items[k]); } return(res); }
// ----------------------------------------------------------------------------- // Parallelism Example: // // Generate a sizable list, and sort it in ascending and descending order, in parallel. // private static void Para(MyContainer <int> .CompareDelegate cmpIntLt, MyContainer <int> .CompareDelegate cmpIntGt) { var rg = new Random(1701); // fix a seed for deterministic results var ic1 = new MyContainer <int>(); for (var i = 0; i < MyContainer <int> .MaxItems; i++) { ic1.Add(rg.Next()); } Console.WriteLine("Input array:"); ic1.Print(); var ic2 = (MyContainer <int>)ic1.Clone(); Console.WriteLine("Sorting a random array ..."); /* sequential code: */ ic1.Sort(cmpIntLt); ic2.Sort(cmpIntGt); /* parallel code: */ Parallel.Invoke( // generate two parallel threads () => ic1.Sort(cmpIntLt), () => ic2.Sort(cmpIntGt)); /* parallelised sorting algorithm: */ ic1.ParSort(cmpIntLt); ic2.ParSort(cmpIntGt); Console.WriteLine("Sorted (ascending):"); ic1.Print(); Console.WriteLine("Sorted?: {0}", ic1.IsSorted(cmpIntLt).ToString()); Console.WriteLine("Sorted (descending):"); ic2.Print(); Console.WriteLine("Sorted?: {0}", ic2.IsSorted(cmpIntGt).ToString()); }