今天来介绍一下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];
--j;
}
arr[j] = temp;
}
Console.WriteLine("排序后结果为:");
foreach (int n in arr)
Console.Write("{0}", n + " ");
Console.WriteLine();
3、选择排序法
int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
foreach (int n in arr)
Console.Write("{0}", n + " ");
Console.WriteLine();
int min;
for (int i = 0; i < arr.Length - 1; i++)
{
min = i;
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[min])
min = j;
}
int t = arr[min];
arr[min] = arr[i];
arr[i] = t;
}
Console.WriteLine("排序后结果为:");
foreach (int n in arr)
Console.Write("{0}", n + " ");
Console.WriteLine();
另外呢,在C#中对数组进行排序微软提供了Sort方法和Reverse方法,Sort方法时从小到大进行排序,Reverse方法对数组元素进行反向排序。