冒泡排序算法以及排序时间的测试
// 吴新强 2013年3月03日23:49:20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Chapter3_Sort
{
class CArray
{
static void Main(string[] args)
{
CArray ca = new CArray(200);
Timing tObj = new Timing();
Random random = new Random(10000);//随机数
for (int i= 0;i < 200;i++)
{
ca.Insert(random.Next(0, 10000));
}
Console.WriteLine("Before Sorting:");//排序前
Console.WriteLine();
ca.DisplayElements();//显示数据
Console.WriteLine(); // 换行
tObj.StartTime();// 测试排序时间的开始时间处
Console.WriteLine();
Console.WriteLine("During Sorting:");//排序中
Console.WriteLine();
ca.BubbleSort();// 调用冒泡排序法进行排序
Console.WriteLine();
tObj.StopTime();// 测试排序时间的截止时间
Console.WriteLine("After Sorting:");//排序后
Console.WriteLine();
ca.DisplayElements();//显示数据
Console.WriteLine();
Console.WriteLine("time( .net):" + tObj.Result().TotalSeconds+" S");// 显示冒泡排序法共使用了多少时间
Console.WriteLine();
}
public void BubbleSort()// 冒泡排序法
{
int temp;
for (int outer = upper; outer >= 1; outer--)
{
for (int inner = 0; inner <= outer - 1; inner++)
{
if ((int)array[inner] > array[inner + 1])
{
temp = array[inner];
array[inner] = array[inner + 1];
array[inner +1] = temp;
}
}
this.DisplayElements();
}
}
private int[] array;
private int upper;
private int numElements;
public CArray(int Size)
{
array = new int[Size];
upper = Size - 1; // upper 最大长度
numElements = 0;// 数组变量
}
public void Insert(int item)
{
array[numElements] = item;
numElements++;
}
public void DisplayElements()// 显示数据
{
for (int i = 0; i <= upper; i++)
Console.Write(array[i] + " ");
}
public void Clear()// 删除数据
{
for (int i = 0; i < upper; i++)
{
array[i] = 0;
numElements = 0;
}
}
}
public class Timing // 时间测试类
{
TimeSpan duration;
public Timing()
{
duration = new TimeSpan(0);
}
public void StopTime()
{
duration=Process.GetCurrentProcess().TotalProcessorTime;
}
public void StartTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
public TimeSpan Result()
{
return duration;
}
}
}
实验结果: