几道经典排序小小理解
1.选择排序
选择排序基本原理:
int[] SeqList={3,9,1,4,2,8,6,5,7};
步骤1:将数字“3”逐一与其他数字比较,发现比3小的数则记录此数(如:1<3)。然后用“1”再与后面的数进行比较,依此类推。
步骤2:将数字 “1”与“3”调换。
private static void SelectSort()
{
int[] SeqList = { 3, 9, 1, 4, 2, 8, 6, 5, 7 };
for (int i = 0; i < SeqList.Length; i++)
{
int k = i; //k是为了记录最小值的下标
for (int j = i + 1; j < SeqList.Length; j++)
{
if (SeqList[k] < SeqList[j]) continue; //始终保证用最小值与其他数比较
k = j; //记录最小值的下标
}
if (k == i) continue;
int temp = SeqList[k];
SeqList[k] = SeqList[i];
SeqList[i] = temp;
}
Console.WriteLine("选择排序结果:" + SeqList.Aggregate("", (current, t) => current + (t + ",")));
}
2.冒泡排序
冒泡排序基本原理:
int[] SeqList={3,9,1,4,2,8,6,5,7};
步骤1:将数字“3”与“9”比较,如大于,则调换。否则则用“9”与“1”比较,如大于则调换。
private static void BubbleSort()
{
int[] SeqList={3,9,1,4,2,8,6,5,7};
for(int i=1;i<SeqList.Length;i++)
{
for(int j=0;j<i;j++)
{
if(SeqList[j]<=SeqList[j+1])continue;
int temp=SeqList[j];
SeqList[j]=SeqList[j+1];
SeqList[j+1]=temp;
}
}
Console.WriteLine("选择排序结果:" + SeqList.Aggregate("", (current, t) => current + (t + ",")));
}
3.希尔排序
基本原理:
int[] SeqList={3,9,1,4,2,8,6,5,7};
步骤1:取得数组长度的一半,如以上数组的一关为 SeqList.Length/2 =4; 使得 SeqList[4] 和SeqList[0] 比较。SeqList[5] 和SeqLis[1]比较i...以此类推...
步骤2:在SeqList/2/2。
private static void ShellSort()
{
int[] SeqList = { 3, 9, 1, 4, 2, 8, 6, 5, 7 };
int half = SeqList.Length/2;
while (half!=0)
{
for (int i = half; i < SeqList.Length; i++)
{
int j;
int temp = SeqList[i];
for (j = i; j >= half; j = j - half)
{
if (temp < SeqList[j- half])
{
SeqList[j] = SeqList[j - half];
}
else
{
break;
}
}
SeqList[j] = temp;
}
half /= 2;
}
Console.WriteLine("希尔排序结果:" + SeqList.Aggregate("", (current, t) => current + (t + ",")));
}