今天來介紹一下C#中遍歷排序的方法,今天就介紹下冒泡法,直接插入法和選擇排序法。
1、冒泡法
題目:使用冒泡法對數組中的元素從小到大進行排序。
方法一:
int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
foreach (int m in arr)
{
Console.Write(m + " ");
}
Console.WriteLine();
int j, temp;
for (int i = 0; i < arr.Length - 1; i++)
{
j = i + 1;
id:
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
goto id;
}
else
{
if (j < arr.Length - 1)
{
j++;
goto id;
}
}
}
foreach (int n in arr)
{
Console.Write(n + " ");
}
Console.WriteLine();
Console.ReadLine();
方法二:
int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
int i, j, temp;
bool done = false;
j = 1;
while ((j < arr.Length) && (!done))
{
done = true;
for (i = 0; i < arr.Length - j; i++)
{
if (arr[i] > arr[i + 1])
{
done = false;
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
j++;
}
foreach (int n in arr)
{
Console.Write(n + "--");
}
Console.WriteLine();
Console.ReadLine();
2、插入排序法
int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
foreach (int n in arr)
Console.Write("{0}", n + " ");
Console.WriteLine();
for (int i = 0; i < 6; ++i)
{
int temp = arr[i];
int j = i;
while ((j > 0) && (arr[j - 1] > temp))
{
arr[j] = arr[j - 1];
&nb