注:本篇文章,未在联系作者以及得到许可的情况下, 禁止以任何形式进行转载。
By:Anders Mail:katrina520@163.com
本BLog里以前发表过类似用C#写的几则排序方法,其中当然也包括冒泡法。不过之前的Code过于臃肿,这次换个角度来写。
题目:给定10个数字:3,7,12,11,35,14,74,98,2,10,将这10个数字按从小到大的顺序输出。
第一种:
using
System;
class ArrayNumbersA
{
public static void Main()
{
int i,j,k,m;
int [] numArrays = { 3 , 7 , 12 , 11 , 35 , 14 , 74 , 98 , 2 , 10 };
for (j = 0 ; j < numArrays.Length; j ++ )
{
k = j;
for (i = j + 1 ; i < 10 ; i ++ )
{
if (numArrays[i] < numArrays[k])
k = i;
}
if (k != j)
{
m = numArrays[j];
numArrays[j] = numArrays[k];
numArrays[k] = m;
}
}
Console.WriteLine( " 排序结果: " );
for (j = 0 ; j < 10 ; j ++ )
Console.WriteLine( " {0} " ,numArrays[j]);
}
}
class ArrayNumbersA
{
public static void Main()
{
int i,j,k,m;
int [] numArrays = { 3 , 7 , 12 , 11 , 35 , 14 , 74 , 98 , 2 , 10 };
for (j = 0 ; j < numArrays.Length; j ++ )
{
k = j;
for (i = j + 1 ; i < 10 ; i ++ )
{
if (numArrays[i] < numArrays[k])
k = i;
}
if (k != j)
{
m = numArrays[j];
numArrays[j] = numArrays[k];
numArrays[k] = m;
}
}
Console.WriteLine( " 排序结果: " );
for (j = 0 ; j < 10 ; j ++ )
Console.WriteLine( " {0} " ,numArrays[j]);
}
}
第二种(与第一种很接近):
using
System;
class ArrayNumbersB
{
static void Main()
{
int [] myArray = new int [] { 3 , 7 , 12 , 11 , 35 , 14 , 74 , 98 , 2 , 10 };
for ( int j = 1 ;j < myArray.Length;j ++ )
{
for ( int i = 0 ;i < myArray.Length - 1 ;i ++ )
{
if ( myArray[i] > myArray[i + 1 ])
{
int temp = myArray[i];
myArray[i] = myArray[i + 1 ];
myArray[i + 1 ] = temp;
}
}
}
Console.WriteLine( " 排序结果: " );
for ( int j = 0 ; j < 10 ; j ++ )
{
Console.WriteLine( " {0} " ,myArray[j]);
}
}
}
class ArrayNumbersB
{
static void Main()
{
int [] myArray = new int [] { 3 , 7 , 12 , 11 , 35 , 14 , 74 , 98 , 2 , 10 };
for ( int j = 1 ;j < myArray.Length;j ++ )
{
for ( int i = 0 ;i < myArray.Length - 1 ;i ++ )
{
if ( myArray[i] > myArray[i + 1 ])
{
int temp = myArray[i];
myArray[i] = myArray[i + 1 ];
myArray[i + 1 ] = temp;
}
}
}
Console.WriteLine( " 排序结果: " );
for ( int j = 0 ; j < 10 ; j ++ )
{
Console.WriteLine( " {0} " ,myArray[j]);
}
}
}