首先定义排序过程中要用到的swap方法,用于交换两个整数的值:
///
/// 交换两个整数的值
///
/// 数1
/// 数2
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();
}
///
/// 冒泡排序
///
/// 传入要排序的数组
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();
}
///
/// 选择排序
///
/// 传入要排序的数组
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]);
}
}
}