计算数组中每个元素的快速排序时间。

问题描述 投票:0回答:1

我有一个练习,我必须比较快速排序与数组中每个元素的时间,并做出图表。 数组有10个不同的元素,这些元素是由Random函数生成的。

我可以用代码计算所有元素的时间。

            Stopwatch MyTimer = new Stopwatch();
            MyTimer.Start();
            Console.WriteLine("Quick Sort: ");
            quickSort(arr);
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + ", ");
            }
            MyTimer.Stop();
            Console.WriteLine("\nTime: " + MyTimer.Elapsed);

但我如何计算这个数组中每个元素的时间呢?

我的所有代码是这样的。

        static void Main(string[] args)
        {
            int[] arr = new int[10];
            shape(arr);
            Console.WriteLine();
            Console.WriteLine("Quick Sort");
            quickSort(arr, 0, 9);
            Console.WriteLine("\nSorted Array is: ");
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
        static public int Partition(int[] arr, int left, int right)
        {
            int pivot;
            pivot = arr[left];
            while (true)
            {
                while (arr[left] < pivot)
                {
                    left++;
                }
                while (arr[right] > pivot)
                {
                    right--;
                }
                if (left < right)
                {
                    int temp = arr[right];
                    arr[right] = arr[left];
                    arr[left] = temp;
                }
                else
                {
                    return right;
                }
            }
        }
        static public void quickSort(int[] arr, int left, int right)
        {
            int pivot;
            if (left < right)
            {
                pivot = Partition(arr, left, right);
                if (pivot > 1)
                {
                    quickSort(arr, left, pivot - 1);
                }
                if (pivot + 1 < right)
                {
                    quickSort(arr, pivot + 1, right);
                }
            }
        }
        static void shape(int[] arr)
        {
            Random rnd = new Random();
            Console.WriteLine("\nArray to sort: ");
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(1, 200);
                Console.Write(arr[i] + ", ");
            }
            Console.WriteLine();
        }
    }
}
c# quicksort
1个回答
0
投票

如果你想计算中间时间,你可以使用ElapsedMilliseconds。

       long[] lapse = new long[arr.Length];
       for (int i = 0; i < arr.Length; i++)
        {
            var timer = MyTimer.ElapsedMilliseconds;
            Console.Write(arr[i] + ", ");
            lapse[i] = MyTimer.ElapsedMilliseconds - timer;  //in millisecond
        }
© www.soinside.com 2019 - 2024. All rights reserved.