空闲复习下冒泡排序看看

排序10000个数字的数组,看看冒泡和Sort()的速度比较:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;



namespace StopWatch

{

    class CArray

    {

        static void Main(string[] args)

        {

            CArray nums = new CArray(10000);

            List<int> nums2 = new List<int>(10000);



            Random rnd = new Random(100000);

            for (int i = 0; i < 10000; i++)

            {

                nums.Insert(rnd.Next(0, 100000));

                nums2.Insert(i, nums.arr[i]);

            }



            Stopwatch sw = new Stopwatch();

            sw.Start();          

            nums.BubbleSort();

            sw.Stop();

            Console.WriteLine("BubbleSort总运行时间:" + sw.Elapsed);

            

            Console.WriteLine("\n");



            Stopwatch sw2 = new Stopwatch();

            sw2.Start();

            nums2.Sort();

            sw2.Stop();

            Console.WriteLine("Sort()总运行时间:" + sw2.Elapsed);



            Console.ReadKey();

        }



        private int[] arr;

        private int upper;

        private int numElements;

        public CArray(int size)

        {

            arr = new int[size];

            upper = size - 1;

            numElements = 0;

        }

        public void Insert(int item)

        {

            arr[numElements] = item;

            numElements++;

        }

        public void Display()

        {

            for (int i = 0; i <= upper; i++)

            {

                Console.Write(arr[i] + " ");

            }

            Console.Write("\n");

        }



        public void BubbleSort()

        {

            int temp;

            for (int outer = upper; outer >= 1; outer--)

            {

                for (int inner = 0; inner <= outer - 1; inner++)

                {

                    if ((int)arr[inner] > arr[inner + 1])

                    {

                        temp = arr[inner];

                        arr[inner] = arr[inner + 1];

                        arr[inner + 1] = temp;

                    }

                }

            }

            //this.Display();

        }

    }

}

输出结果为:

BubbleSort总运行时间:00:00:00.8866538
Sort()总运行时间:00:00:00.0009665

 

你可能感兴趣的:(冒泡排序)