暇な復習の下で泡の順序をつけてみます

6753 ワード

10,000個の数字の配列を並べて、泡と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("
"); 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("
"); } 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:00.88666538 Sort()総稼働時間:00:00:00:0.0009665