c# 冒泡排序
using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace sort
{
class bubblesorter
{
public static int[] sort(int[] a)
{
bubblesort(a);
return a;
}
private static void bubblesort(int[] myarray)
{
for (int i = 0; i < myarray.length; i++)//循环的趟数
{
for (int j = 0; j < myarray.length - 1- i; j++)//每次循环的次数
{
//比较相邻元素,将值大的后移==》每一趟循环结束==》最后一个数是最大的。
//所以每次循环都比上一次循环的个数少1,即j < myarray.length - 1- i
if (myarray[j] > myarray[j + 1])
{
swap(ref myarray[j], ref myarray[j + 1]);
}
}
}
}
//引用参数与值参数
private static void swap(ref int left, ref int right)
{
int temp;
temp = left;
left = right;
right = temp;
}
}
}
冒泡排序算法的运作如下:
冒泡排序算法的运作如下:
1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。==》最后一个数就不需要比较了,因为它就是最大的。
3、针对所有的元素重复以上的步骤,除了最后一个。
4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
以上就是 c# 冒泡排序的内容。
