public class SelectionSort
{
public static int[] Sort(int[] array)
{
int[] copyArray = new int[array.Length];
Array.Copy(array, copyArray, array.Length);
// 总共要经过 N-1 轮比较
for (int i = 0; i < copyArray.Length - 1; i++)
{
int min = i;
// 每轮需要比较的次数 N-i
for (int j = i + 1; j < copyArray.Length; j++)
{
if (copyArray[min] > copyArray[j])
{
// 记录目前能找到的最小值元素的下标
min = j;
}
}
// 将找到的最小值和i位置所在的值进行交换
if (i != min)
{
int tmp = copyArray[i];
copyArray[i] = copyArray[min];
copyArray[min] = tmp;
}
}
return copyArray;
}
}
public class InsertSort
{
public static int[] Sort(int[] array)
{
int[] copyArray = new int[array.Length];
array.CopyTo(copyArray, 0);
for (int i = 1; i < copyArray.Length; i++)
{
int temp = copyArray[i];
int j = i;
while (j > 0 && temp < copyArray[j-1])
{
copyArray[j] = copyArray[j-1];
j--;
}
if (j!=i)
{
copyArray[j]=temp;
}
}
return copyArray;
}
}
public class BubbleSort
{
public static int[] _Sort(int[] array)
{
int[] copyArray = new int[array.Length];
array.CopyTo(copyArray, 0);
for (int i = copyArray.Length - 1; 0 < i; i--)
{
for (int j = i - 1; 0 <= j; j--)
{
if (copyArray[j] > copyArray[i])
{
int temp = copyArray[j];
copyArray[j] = copyArray[i];
copyArray[i] = temp;
}
}
}
return copyArray;
}
public static int[] Sort(int[] array)
{
int[] copyArray = new int[array.Length];
array.CopyTo(copyArray, 0);
for (int i = 1; i < copyArray.Length; i++)
{
for (int j = 0; j < copyArray.Length - i; j++)
{
if (copyArray[j] > copyArray[j + 1])
{
int temp = copyArray[j];
copyArray[j] = copyArray[j + 1];
copyArray[j + 1] = temp;
}
}
}
return copyArray;
}
}
public class Main
{
public Main()
{
var randomArray = generateArray(15, 3, 29);
Console.WriteLine(string.Join(',', randomArray));
var sort = BubbleSort.Sort(randomArray);
Console.WriteLine("Bubble Sort:" + string.Join(',', sort));
sort = SelectionSort.Sort(randomArray);
Console.WriteLine("Selection Sort:" + string.Join(',', sort));
sort = InsertSort.Sort(randomArray);
Console.WriteLine("Insert Sort:" + string.Join(',', sort));
}
static int[] generateArray(int length, int mix, int max)
{
int[] array = new int[length];
Hashtable table = new Hashtable();
Random random = new Random();
for (int i = 0; table.Count < length; i++)
{
var data = random.Next(mix, max);
if (!table.ContainsKey(data) && data != 0)
{
table.Add(data, data);
array[table.Count - 1] = data;
}
}
return array;
}
}