Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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<int> 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<int> 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);
- }
- /// <summary>Generates an array of random integers.</summary>
- /// <param name="count">Number of integers to generate.</param>
- /// <returns>Array of random integers.</returns>
- 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;
- }
- /// <summary>Sorts the given integers in parallel.</summary>
- /// <param name="integers">Enumeration of integers to sort.</param>
- /// <returns>Sorted enumeration of integers.</returns>
- static IEnumerable<int> SortInParallel(IEnumerable<int> integers)
- {
- return integers.AsParallel().OrderBy((i) => i);
- }
- /// <summary>Confirms that the given integers are in sorted order.</summary>
- /// <param name="integers">Enumeration of integers to check.</param>
- /// <returns>
- /// If <paramref name="integers"/> is in ascending sorted order, <c>true</c>.
- /// Otherwise, <c>false</c>.
- /// </returns>
- static bool ConfirmSort(IEnumerable<int> integers)
- {
- int last = integers.First();
- foreach (int current in integers.Skip(1))
- {
- if (last > current)
- return false;
- last = current;
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement