冒泡排序速記口訣(升序):
N個數字來排隊,兩兩相比小靠前。
外層循環N-1,內層循環N-1-i.
如果降序排序,只要把握程序中的大于號換成小于號就行了。
如實現隨即輸入6個人的成績,按從小到大的順序排列
參考代碼:
static void Main(string [] args)
{
int [ ] scores=new int [6];
int i,j; //循環變量
int temp; //臨時變量
//讀入成績
Console.WriteLine("請輸入6個數字:");
for(int i=0;i<6;i++)
{
Console.WriteLine("請輸入第{0}個數字:",i+1);
score[i]=int.Parse(Console.ReadLine());
}
//開始排序
for(int i=0;i<scores.Length-1;i++)
{
for(j=0;j<score.Length-1-i;j++)
{
if(scores[j]<scores[j+1])
{
//交換元素
temp=secores[j];
scores[j]=scores[j+1];
scores[l+1]=temp;
}
}
}
//排序后輸出
Console.WriteLine("排序后的成績為:");
for(int i=0;i<6;i++)
{
Console.WriteLine("{0}\t",scores[i]);
}
Console.ReadLine();
}