快速排序比普通的交互式排序慢吗?

时间:2019-11-28 11:11:18

标签: c# quicksort

快速排序比普通的交互式排序慢吗?

我已经在Visual Studio中检查了控制台应用程序。我在这里犯任何错误还是请告诉我原因。输出显示迭代排序比QUick排序有效得多

class Program
    {
        static Random rr = new Random();
        private static void Quick_Sort(int[] arr, int left, int right)
        {
            if (left < right)
            {
                int pivot = Partition(arr, left, right);

                if (pivot > 1)
                {
                    Quick_Sort(arr, left, pivot - 1);
                }
                if (pivot + 1 < right)
                {
                    Quick_Sort(arr, pivot + 1, right);
                }
            }

        }

        private static int Partition(int[] arr, int left, int right)
        {

            int pivot = arr[9];

            while (true)
            {

                while (arr[left] < pivot)
                {
                    left++;
                }

                while (arr[right] > pivot)
                {
                    right--;
                }

                if (left < right)
                {
                    if (arr[left] == arr[right]) return right;

                    int temp = arr[left];
                    arr[left] = arr[right];
                    arr[right] = temp;
                }
                else
                {
                    return right;
                }
            }
        }


        static void Main(string[] args)
        {
            int[] arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6, 27 };



            Stopwatch sw = new Stopwatch();

            sw.Reset();
            sw.Start();
            Quick_Sort(arr, 0, arr.Length - 1);
            sw.Stop();

            Console.WriteLine(sw.ElapsedTicks.ToString());
            sw.Reset();
            arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6, 27 };
            sw.Start();
            for (int i = 0; i < arr.Length; i++)
            {
                for (int j = i; j < arr.Length; j++)
                {
                    if (arr[i] > arr[j])
                    {
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedTicks.ToString());
            //Console.WriteLine();
            //Console.WriteLine("Sorted array : ");

            foreach (var item in arr)
            {
                Console.Write(" " + item);
            }
            Console.WriteLine();
            Console.ReadKey();



        }
    }

输出

快速排序-3071个滴答 正常排序-7个滴答声

0 个答案:

没有答案