此處使用C#控制台
方法一:直接使用if判斷語句進行排序(此處應用到冒泡排序的思想)
Console.WriteLine("請輸入五個數字:");
int a,b,c,d,e,t;
a=int.Parse(Console.ReadLine());
b=int.Parse(Console.ReadLine());
c=int.Parse(Console.ReadLine());
d=int.Parse(Console.ReadLine());
e=int.Parse(Console.ReadLine());
if( a < b) { t = a; a = b; b = t;}
if (a < c) { t = a; a = c; c = t; }
if (a < d) { t = a; a = d; d = t; }
if (a < e) { t = a; a = e; e = t; }
if (b < c) { t = b; b = c; c = t; }
if (b < d) { t = b; b = d; d = t; }
if (b < e) { t = b; b = e; e = t; }
if (c < d) { t = c; c = d; d = t; }
if (c < e) { t = c; b = d; d = t; }
if (d < e) { t = d; d = e; e = t; }
Console.WriteLine("輸出結果為:{0}>{1}>{2}>{3}>{4}",a,b,c,d,e);
Console.ReadKey();
此處附加優化(方法提取):
方法二:使用冒泡排序
int[]arr = new int[5];
for(int i= 0; i<arr.Length;i++){
Console.WriteLine("請輸入第{0}個數字",i+1);
arr[i]=int.Parse(Console.ReadLine());
}
int x = 0;
for (int i = 0; i < a.Length - 1; i++)//外循環為排序趟數,len個數進行len-1趟
{
for (int j = 0; j < a.Length - 1 - i; j++)// 內循環為每趟比較的次數,第i趟比較len-i次
{
if (a[j] < a[j + 1])//相鄰的兩個元素進行比較,若是從大到小則進行交換(即大的在左,小的在右)
{
x = a[j + 1];
a[j + 1] = a[j];
a[j] = x;
}
}
}
Console.WriteLine("輸出結果為:");
for(int i= 0; i<arr.Length;i++){
Console.Write("{0}>",arr[i]);
}