排序算法测出的时间以理论不符,求讨论
最近在复习c#写的插入排序,冒泡排序,选择排序的时间消耗。理论上插入排序效率最低,所花时间应该最长,但是我换了几种方法测试,结果统计出来的时间插入排序最少。其中原因有哪些可能呢?。。程序代码:
using System; using Sorts.Sorts; using System.Diagnostics; namespace Sorts { class Program { static void Main() { System.IntPtr ptr = new IntPtr(0x0001); Process.GetCurrentProcess().ProcessorAffinity = ptr; double insertresult = 0.0; double bubbleresult = 0.0; double selectionresult = 0.0; Stopwatch watch1 = new Stopwatch(); Stopwatch watch2 = new Stopwatch(); Stopwatch watch3 = new Stopwatch(); Timing sortTime = new Timing(); for (int i = 0; i < 120; i++) { DataSource t = new DataSource(2000); t.FullDataSource(2000, 0, 100); DataSource p = new DataSource(t); DataSource q = new DataSource(t); BubbleSortClass bubblesort = new BubbleSortClass(q); //sortTime.StartIt(); watch1.Start(); bubblesort.BubbleSort(); watch1.Stop(); bubbleresult += watch1.ElapsedMilliseconds; watch1.Reset(); SelectionSortClass selectionsort = new SelectionSortClass(p); //sortTime.StartIt(); watch2.Start(); selectionsort.SelectionSort(); watch2.Stop(); selectionresult += watch2.ElapsedMilliseconds; watch2.Reset(); InsertSortClass insertsort = new InsertSortClass(t); //sortTime.StartIt(); watch3.Start(); insertsort.InsertSort(); watch3.Stop(); insertresult += watch3.ElapsedMilliseconds; watch3.Reset(); } Console.WriteLine("冒泡排序所花时间为:" + bubbleresult / 120); Console.WriteLine("选择排序所花时间为:" + selectionresult / 120); Console.WriteLine("插入排序所花时间为:" + insertresult / 120); Console.Read(); } } }其中datasource是封装了数组的数据源