前言
下午开发一个功能涉及到排序,这里就列举集中并作简单性能对比。本文是作为记录用的也就不多废话了,直接上代码。
public class Sort
{
public void Test()
{
int Num = 10000;
int[] iArrary = GetList(Num);
Stopwatch watch = new Stopwatch();
watch.Start();
BubbleSorter(iArrary);
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//Desplay(iArrary);
iArrary = GetList(Num);
watch.Reset();
watch.Start();
SelectionSorter(iArrary);
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//Desplay(iArrary);
iArrary = GetList(Num);
watch.Reset();
watch.Start();
InsertionSorter(iArrary);
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//Desplay(iArrary);
iArrary = GetList(Num);
watch.Reset();
watch.Start();
ShellSorter(iArrary);
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//Desplay(iArrary);
}
private int[] GetList(int Num)
{
int[] array = new int[Num];
Random rd = new Random();
for (int i = 0; i < Num; i++)
{
array[i] = rd.Next(0, Num);
}
return array;
}
private void Desplay(int[] list)
{
foreach (int item in list)
{
Console.WriteLine(item.ToString());
}
}
/// <summary>
/// 冒泡排序
/// </summary>
/// <param name="list"></param>
public void BubbleSorter(int[] list)
{
int i, j, temp;
bool done = false;
j = 1;
while ((j < list.Length) && (!done))
{
done = true;
for (i = 0; i < list.Length - j; i++)
{
if (list[i] > list[i + 1])
{
done = false;
temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
}
}
j++;
}
}
/// <summary>
/// 选择排序
/// </summary>
/// <param name="list"></param>
public void SelectionSorter(int[] list)
{
int min;
for(int i=0;i<list.Length-1;i++)
{
min=i;
for(int j=i+1;j<list.Length;j++)
{
if(list[j]<list[min])
min=j;
}
int t=list[min];
list[min]=list[i];
list[i]=t;
}
}
/// <summary>
/// 插入排序
/// </summary>
/// <param name="list"></param>
public void InsertionSorter(int[] list)
{
for(int i=1;i<list.Length;i++)
{
int t=list[i];
int j=i;
while((j>0)&&(list[j-1]>t))
{
list[j]=list[j-1];
--j;
}
list[j]=t;
}
}
/// <summary>
/// 希尔排序
/// </summary>
/// <param name="list"></param>
public void ShellSorter(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;
}
}
}
}
num=100 则四种算法都是0MS。
num=1000 冒泡6,选择3,插入2,希尔2
num=10000 冒泡612,选择309,插入189,希尔182
做个简单记录