class Program
{
static void Main(string[] args)
{
int[] unsort = { 2, 4, 3, 6, 7, 5, 6, 1, 8, 9, 3, 0 };
//int[] unsort = { 2, 0};
//bubble(unsort);
// selectionSort(unsort);
//insertionSort(unsort);
//insert_sort(unsort, 12);
MergeSort(ref unsort);
printSort(unsort);
}
static void printSort(int[] array)
{
foreach (int item in array)
Console.Write(item + " ");
Console.WriteLine();
}
static void bubble(int[] array)
{
for (int i = 0; i <= array.Length - 1; i++)//扫描的遍数
{
for (int j = 0; j <= array.Length - 1 - i - 1; j++)//每次扫描,最大的沉底,然后可以少扫描一个。
{
if (array[j] > array[j + 1])
{
int tmp = array[j + 1];
array[j + 1] = array[j];
array[j] = tmp;
}
}
Console.WriteLine(string.Format("第{0}遍", i));
printSort(array);
}
}
static void selectionSort(int[] array)
{
for (int i = 0; i <= array.Length - 1; i++)//数组中的元素依次取出与后续的比
{
for (int j = i; j <= array.Length - 1; j++)//后续的元素
{
if (array[i] > array[j])
{
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
Console.WriteLine(string.Format("第{0}遍", i));
printSort(array);
}
}
static void insertionSort(int[] array)
{
for (int i = 1; i <= array.Length - 1; i++)
{
for (int j = 0; j <= i - 1; j++)
{
if (array[i] >= array[j] && array[i] < array[j + 1])
{
insertArray(array, i, j + 1);//此方法专门实现插入和后移
}
else if (array[i] < array[j])
{
insertArray(array, i, 0);
}
}
Console.WriteLine(string.Format("第{0}遍", i));
printSort(array);
}
}
//待排序元素用一个数组a表示,数组有n个元素
static void insert_sort(int[] array, int n)
{
int i, j;
int t;
for (i = 1; i < n; i++) //i表示插入次数,共进行n-1次插入
{
t = array[i]; //把待排序元素赋给t
j = i - 1;
while ((j >= 0) && (t < array[j]))
{
array[j + 1] = array[j];
j--;
} // 顺序比较和移动// 此法妙哉!
array[j + 1] = t;
Console.WriteLine(string.Format("第{0}遍", i));
printSort(array);
}
}
static void insertArray(int[] array, int from, int to)//从from移到to,from>=to
{
if (from >= to)
{
int tmp = array[from];
for (int i = from; i >= to + 1; i--)
{
array[i] = array[i - 1];
}
array[to] = tmp;
}
}
//归并排序
static void MergeSort(ref int[] array)
{
if (array.Length > 1)
{
int i = array.Length / 2;
int[] left = new int[i];
for (int index = 0; index < left.Length; index++)
{
left[index] = array[index];
}
MergeSort(ref left);
int[] right = new int[array.Length - i];
for (int index = 0; index < right.Length; index++)
{
right[index] = array[index + i];
}
MergeSort(ref right);
array = Two_Way_Merge_Sort(left, right);
}
}
static public int[] Two_Way_Merge_Sort(int[] A, int[] B)
{
int[] C = new int[A.Length + B.Length];
int k = 0;
int i = 0;
int j = 0;
while (i < A.Length && j < B.Length)
{
if (A[i] < B[j])
{
C[k] = A[i];
k++;
i++;
}
else
{
C[k] = B[j];
k++;
j++;
}
}
while (i < A.Length)
C[k++] = A[i++];
while (j < B.Length)
C[k++] = B[j++];
return C;
}
}