using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;//产生随机数时用到
/// <summary>
/// 测试方法
/// </summary>
class SortTest
{
readonly int N = 40;
readonly int FullNum = 100;
public void FullDo()
{
for (int i = 0; i < FullNum; i++)
{
this.Do();
}
Console.WriteLine("Full Do: " + FullNum + " times.Array Len:" + N);
}
public void Do()
{
byte[] buff = new byte[2];
RNGCryptoServiceProvider pri = new RNGCryptoServiceProvider();
int[] Arr = new int[N];
for(int i=0;i<N;i++)
{
pri.GetBytes(buff);
int temp = BitConverter.ToInt16(buff, 0);
Arr[i] = temp;
}
int[] goodArr = new int[N];
Arr.CopyTo(goodArr, 0);
Array.Sort(goodArr);
//InsertSort ins = new InsertSort();
//ins.Insert_sort(Arr, N);
SelSort algo = new SelSort();
algo.Do(Arr, N);
for (int i = 0; i < N; i++)
{
if (goodArr[i] != Arr[i])
{
throw new Exception("not equal " + i);
}
}
Console.WriteLine("all equal");
}
}
/// <summary>
/// 快速排序
/// </summary>
class QuickSort
{
public void Sort(int[] K, int s, int t)
{
if (s < t)
{
int i = s;
int j = t + 1;
int temp = K[s];
while (true)
{
do
{
i++;
}
while (temp > K[i] && i != t);
do
{
j--;
}
while (temp < K[j] && j != s);
if (i < j)
{
Swap(ref K[i],ref K[j]);
}
else
{
goto LabelOut;
}
}
LabelOut: Swap(ref K[s], ref K[j]);
Sort(K, s, j - 1);//j 的左边总小于等于K[j],j的右边总大于等于K[j];
Sort(K, j + 1, t);
}
}
public void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}
/// <summary>
/// 选择排序
/// </summary>
class SelSort
{
public void Dox(int [] K, int N)
{
for (int i = 0; i < N-1; i++)
{
int indexMin = i;
for (int j = i+1; j < N; j++)
{
if (K[j] < K[indexMin])
{
indexMin = j;
}
}
if (indexMin != i)
{
int temp = K[indexMin];
K[indexMin] = K[i];
K[i] = temp;
}
}
}
}
/// <summary>
/// 插入排序
/// </summary>
class InsertSort
{
public void Insert_sortx(int[] K, int n)
{
for (int i = 1; i < n; i++)
{
int insertnode = K[i];
int j = i - 1;//
while (j >= 0 && insertnode < K[j])
{
K[j + 1] = K[j];
j--;
}
K[j + 1] = insertnode;
}
}
}