namespace BubbleSorter
{
class BubbleSorter
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
BubbleSort(myArray);
}
public static void BubbleSort(int[] myArray)
{
for (int i = 0; i < myArray.Length-1; i++) //由于数组的特点,从0开始,但myArray的长度为5,所以需要减1,实际进行了(0~3)4趟循环 {
for (int j =0; j < myArray.Length -1- i; j++) //内层循环的要点是相邻比较。当j=4的时候,就推出循环了 {
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;
}
static void Main(string[] args)
{
int[] a = { 2, 1, 5, 10, 9 };
BubbleSorter.Sort(a);
foreach (int i in a)
{
Console.WriteLine(i);
}
Console.Read();
}
}
}