排序算法实验
一、插入排序算法
1、插入排序算法,利用List<int>特性测试小数据量排序。
这个算法可以理解为打扑克牌,然后拿牌的时候进行排序。10万次运算,650ms左右执行完毕。下面是测试代码:
int[] intArray = new int[] { 1, 7, 8, 3, 5, 6, 9, 13, 22, 11, 111, 55, 48, 37 };
List<int> list = new List<int>();
Stopwatch watch = new Stopwatch();
for (int k = 0; k < 100000; k++) //k次运算
{
intArray = new int[] { 1, 7, 8, 3, 5, 6, 9, 13, 22, 11, 111, 55, 48, 37 };
list = new List<int>();
//计时
watch.Start();
list.Add(intArray[0]);
for (int i = 1; i < intArray.Length - 1; i++)
{
int tmp = intArray[i];
bool insert = false;
for (int j = 0; j < list.Count; j++)
{
if (list[j] > tmp) //找到比自身大的值,则插入该位置
{
list.Insert(j, tmp);
insert = true;
break;
}
}
if (!insert) //没有找到比自身大的值,则添加到最后
list.Add(tmp);
}
//停止计时
watch.Stop();
}
Console.WriteLine(watch.ElapsedMilliseconds.ToString() + "毫秒");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.ReadKey();
List<int> list = new List<int>();
Stopwatch watch = new Stopwatch();
for (int k = 0; k < 100000; k++) //k次运算
{
intArray = new int[] { 1, 7, 8, 3, 5, 6, 9, 13, 22, 11, 111, 55, 48, 37 };
list = new List<int>();
//计时
watch.Start();
list.Add(intArray[0]);
for (int i = 1; i < intArray.Length - 1; i++)
{
int tmp = intArray[i];
bool insert = false;
for (int j = 0; j < list.Count; j++)
{
if (list[j] > tmp) //找到比自身大的值,则插入该位置
{
list.Insert(j, tmp);
insert = true;
break;
}
}
if (!insert) //没有找到比自身大的值,则添加到最后
list.Add(tmp);
}
//停止计时
watch.Stop();
}
Console.WriteLine(watch.ElapsedMilliseconds.ToString() + "毫秒");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.ReadKey();
把List初始化为list = new List<int>(intArray.Length);让它容量刚好是要插入数的个数,还可以节约50ms左右。这个是避免数组扩容的开销。
2、交换排序
对比前后两位,大的排到后面
Stopwatch watch = new Stopwatch();
int[] intArray = null;
for (int k = 0; k < 100000; k++) //k次运算
{
intArray = new int[] { 1, 7, 8, 3, 5, 6, 9, 13, 22, 11, 111, 55, 48, 37 };
watch.Start();
int ptr = 0;
int tmp = 0;
bool ischange = false;
while (true)
{
if (tmp > intArray[ptr])
{
intArray[ptr - 1] = intArray[ptr];
intArray[ptr] = tmp;
ischange = true;
}
if (++ptr >= intArray.Length)
{
ptr = 1;
if (!ischange)
break;
ischange = false;
}
tmp = intArray[ptr - 1];
}
watch.Stop();
}
Console.WriteLine(watch.ElapsedMilliseconds.ToString() + "毫秒");
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
Console.ReadKey();
int[] intArray = null;
for (int k = 0; k < 100000; k++) //k次运算
{
intArray = new int[] { 1, 7, 8, 3, 5, 6, 9, 13, 22, 11, 111, 55, 48, 37 };
watch.Start();
int ptr = 0;
int tmp = 0;
bool ischange = false;
while (true)
{
if (tmp > intArray[ptr])
{
intArray[ptr - 1] = intArray[ptr];
intArray[ptr] = tmp;
ischange = true;
}
if (++ptr >= intArray.Length)
{
ptr = 1;
if (!ischange)
break;
ischange = false;
}
tmp = intArray[ptr - 1];
}
watch.Stop();
}
Console.WriteLine(watch.ElapsedMilliseconds.ToString() + "毫秒");
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
Console.ReadKey();
用自身数组搞定,耗时少一些,大概450ms搞定。