static void Main(string[] args)
        {
            const int     numberOfElements = 20000000;
            DataGenerator dataGenerator    = new DataGenerator();

            dataGenerator.Generate(numberOfElements);

            for (int i = 0; i < 3; i++)
            {
                long[] numbers   = dataGenerator.GetNumbers();
                var    stopwatch = new Stopwatch();

                Console.WriteLine("QuickSort By Recursive Method - run # {0}", i);
                stopwatch.Reset();
                stopwatch.Start();
                QuickSortSingleThread.SerialQuicksort(numbers, 0, numberOfElements - 1);
                stopwatch.Stop();

                var singleThreadRuntime = stopwatch.ElapsedMilliseconds;

                System.Console.WriteLine("Single thread calculation runtime: {0} ms", singleThreadRuntime);
                stopwatch.Reset();
                stopwatch.Start();
                QuickSortMultipleSingleThread.SerialQuicksort(numbers, 0, numberOfElements - 1).Wait();
                stopwatch.Stop();

                var multithreadRuntime = stopwatch.ElapsedMilliseconds;
                System.Console.WriteLine("MultiThread thread calculation runtime: {0} ms", multithreadRuntime);
            }
        }
Esempio n. 2
0
        public static async Task SerialQuicksort(long[] elements, long left, long right)
        {
            long i = left, j = right;
            var  pivot = elements[(left + right) / 2];

            while (i <= j)
            {
                while (elements[i].CompareTo(pivot) < 0)
                {
                    i++;
                }
                while (elements[j].CompareTo(pivot) > 0)
                {
                    j--;
                }

                if (i <= j)
                {
                    // Swap
                    var tmp = elements[i];
                    elements[i] = elements[j];
                    elements[j] = tmp;

                    i++;
                    j--;
                }
            }

            // Recursive calls
            if (left - right < 2000)
            {
                if (left < j)
                {
                    QuickSortSingleThread.SerialQuicksort(elements, left, j);
                }
                if (i < right)
                {
                    QuickSortSingleThread.SerialQuicksort(elements, i, right);
                }
            }
            else
            {
                var t1 = left < j?SerialQuicksort(elements, left, j) : Task.CompletedTask;

                var t2 = i < right?SerialQuicksort(elements, i, right) : Task.CompletedTask;

                await Task.WhenAll(t1, t2).ConfigureAwait(false);
            }
        }