测试环境说明:
Win-XP下,VS2008,主频:core2 双核2.53GHZ
下面是测试的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace TestSort
{
class Program
{
static void Main(string[] args)
{
int MaxValue = 10000;
int[] sortPre = GenerateintList(MaxValue);
Console.WriteLine("随机数产生完毕!");
//DateTime SelectPreTime = System.DateTime.Now;
//SelectSort(sortPre);
//DateTime SelectAfterTime = System.DateTime.Now;
//TimeSpan Selectspan = SelectAfterTime - SelectPreTime;
DateTime ShellPreTime = System.DateTime.Now;
ShellSort(sortPre);
DateTime ShellAfterTime = System.DateTime.Now;
TimeSpan Shellspan = ShellAfterTime - ShellPreTime;
//DateTime RaisePreTime = System.DateTime.Now;
//RaiseSort(sortPre);
//DateTime RaiseAfterTime = System.DateTime.Now;
//TimeSpan Raisespan = RaiseAfterTime - RaisePreTime;
//Console.WriteLine("选择排序用时:" + Selectspan.TotalMilliseconds.ToString() + "毫秒");
Console.WriteLine("希尔排序用时:" + Shellspan.TotalMilliseconds.ToString() + "毫秒");
//Console.WriteLine("冒泡排序用时:" + Raisespan.TotalMilliseconds.ToString() + "毫秒");
Console.ReadKey();
}
//产生随机数
private static int[] GenerateintList(int maxValue)
{
int[] intArr = new int[maxValue];
ArrayList intList = new ArrayList(maxValue);
Random random = new Random();
for (; intList.Count < intList.Capacity; )
{
int cellint = random.Next(1, maxValue + 1);
if (!intList.Contains(cellint))
intList.Add(cellint);
}
for (int index = 0; index < intList.Capacity; index++)
{
intArr[index] = (int)intList[index];
}
return intArr;
}
//选择排序
public static void SelectSort(int[] sourceArr)
{
int i = 0, j = 0;
for (; i < sourceArr.Length; i++)
{
j = i + 1;
for (; j < sourceArr.Length; j++)
{
if (sourceArr[j] < sourceArr[i])
{
int temp = sourceArr[j];
sourceArr[j] = sourceArr[i];
sourceArr[i] = temp;
}
}
}
}
//希尔排序
public static void ShellSort(int[] list)
{
int inc;
for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
for (; inc > 0; inc /= 3)
{
for (int i = inc + 1; i <= list.Length; i += inc)
{
int t = list[i - 1];
int j = i;
while ((j > inc) && (list[j - inc - 1] > t))
{
list[j - 1] = list[j - inc - 1];
j -= inc;
}
list[j - 1] = t;
}
}
}
//冒泡排序
public static void RaiseSort(int[] list)
{
for(int j = 1 ; j<list.Length;j++)
{
for(int i=0;i<list.Length-1;i++)
{
if(list[i]>list[i+1])
{
int temp = list[i+1];
list[i+1] = list[i];
list[i] = temp;
}
}
}
}
}
}
希尔排序测试了3次,分别是:156.26毫秒、140.625毫秒、140.625毫秒; 平均:145.84毫秒
选择排序测试了3次,分别是:437.5毫秒、437.5毫秒、453.125毫秒,平均:442.71毫秒
冒泡排序测试了3次,分别是:609.375毫秒、609.375毫秒、609.375毫秒,平均:609.375毫秒
结论:希尔排序法 >> 选择排序法 > 冒泡排序法