// 2013年3月13日19:19:01 吴新强
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace Chapter3_SelectionSort
{
class CArray
{
static void Main(string[] args)
{
CArray ca = new CArray(10);
Timing tObj = new Timing();
Random random = new Random(100);//随机数
for (int i = 0; i < 10; i++)
{
ca.Insert(random.Next(0, 100));
}
Console.WriteLine("SelectionSort Before Sorting:");//排序前
Console.WriteLine();
ca.DisplayElements();//显示数据
Console.WriteLine(); // 换行
tObj.StartTime();// 测试排序时间的开始时间处
Console.WriteLine();
Console.WriteLine("SelectionSort During Sorting:");//排序中
Console.WriteLine();
ca.SelectionSort();// 调用选择排序法进行排序
Console.WriteLine();
tObj.StopTime();// 测试排序时间的截止时间
Console.WriteLine("SelectionSort After Sorting:");//排序后
Console.WriteLine();
ca.DisplayElements();//显示数据
Console.WriteLine();
Console.WriteLine("SelectionSort time( .net):" + tObj.Result().TotalMilliseconds + " MS");// 显示选择排序法共使用了多少时间
Console.WriteLine();
ca.Clear();
}
public void SelectionSort()// 选择排序法
{
int temp, min;
for (int outer = 0; outer <= upper; outer++)
{
min = outer;
for (int inner = outer + 1; inner <= upper; inner++)
{
if (array[inner] < array[min])
{
min = inner;
}
temp = array[outer];
array[outer] = array[min];
array[min]= 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;
}
}
}
/*class CArray
{
private int[] array;
private int upper;
private int numElements;
public CArray(int Size)
{
array = new int[Size];
upper = Size - 1;
numElements = 0;
}
public void Insert(int item)
{
array[numElements] = item;
numElements++;
}
public void DisplayElements()
{
for (int i = 0; i <= upper; i++)
Console.WriteLine(array[i] + "");
}
public void Clear()
{
for (int i = 0; i < upper i++)
{
array [i]=0;
numElements=0;
}
}
}
}*/
实验结果: