using System; using System.Collections.Generic; using System.Linq; namespace ParallelSort { class Program { static void Main(string[] args) { // Stopwatch for timing operations. System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); long count = long.Parse(args[0]); // Generate the numbers! This part is easy enough. It generates them // in an array rather than yield return to prevent lazy evaluation. System.Console.Write("Generating {0} integers...", count); stopwatch.Restart(); IEnumerable integers = GenerateRandoms(count); stopwatch.Stop(); Console.WriteLine(" {0}ms.", stopwatch.ElapsedMilliseconds); // This timer is actually useless, since the sort is not evaluated until the next step... System.Console.Write("Sorting integers..."); stopwatch.Restart(); IEnumerable sortedIntegers = SortInParallel(integers); stopwatch.Stop(); Console.WriteLine(" {0}ms.", stopwatch.ElapsedMilliseconds); // Confirm the sorting. This part is a single-core algorithm, because // there's no real way to do it in LINQ without blowing away memory. System.Console.Write("Confirming sort..."); stopwatch.Restart(); bool confirmed = ConfirmSort(sortedIntegers); stopwatch.Stop(); if (confirmed) System.Console.WriteLine(" {0}ms.", stopwatch.ElapsedMilliseconds); else System.Console.WriteLine(" FAIL - {0}ms.", stopwatch.ElapsedMilliseconds); } /// Generates an array of random integers. /// Number of integers to generate. /// Array of random integers. static int[] GenerateRandoms(long count) { Random random = new Random(); int[] array = new int[count]; for (int index = 0; index < count; ++index) array[index] = random.Next(); return array; } /// Sorts the given integers in parallel. /// Enumeration of integers to sort. /// Sorted enumeration of integers. static IEnumerable SortInParallel(IEnumerable integers) { return integers.AsParallel().OrderBy((i) => i); } /// Confirms that the given integers are in sorted order. /// Enumeration of integers to check. /// /// If is in ascending sorted order, true. /// Otherwise, false. /// static bool ConfirmSort(IEnumerable integers) { int last = integers.First(); foreach (int current in integers.Skip(1)) { if (last > current) return false; last = current; } return true; } } }