C#实现整数冒泡排序、选择排序
时间:2011-02-15 来源:zhouhb
/// <summary>
/// 交换两个整数的值
/// </summary>
/// <param name="aa">数1</param>
/// <param name="bb">数2</param>
private static void Swap(ref int aa,ref int bb)
{
int temp;
temp = bb;
bb = aa;
aa = temp;
}
// 冒泡排序
class Program
{
static void Main(string[] args)
{
int[] a={1,2,5,7,9,8,10,6,4,3};
BubbleSort(a);
for (int i = 0; i < a.Length; i++)
Console.Write(a[i] + " ");
Console.ReadKey();
}
/// <summary>
/// 冒泡排序
/// </summary>
/// <param name="a">传入要排序的数组</param>
private static void BubbleSort(int[] a)
{
for (int i = 0; i < a.Length - 1; i++)
{
for (int j = 0; j < a.Length - i - 1; j++)
{
if (a[j] < a[j + 1])//降序排列
{
Swap(ref a[j], ref a[j + 1]);
}
}
}
}
}
//选择排序
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 4, 3,6,5,7,9,8 };
SelectionSort(a);
for (int i = 0; i < a.Length; i++)
Console.Write(a[i] + " ");
Console.ReadKey();
}
/// <summary>
/// 选择排序
/// </summary>
/// <param name="a">传入要排序的数组</param>
private static void SelectionSort(int[] a)
{
int k;
for (int i = 0; i < a.Length - 1; i++)
{
k = i;
for (int j = i+1; j < a.Length ; j++)
{
if (a[j] < a[k])//升序排列
{
k = j;
}
}
if(k!=i)
Swap(ref a[i], ref a[k]);
}
}
}