一个冒泡排序程序,將交换数组的两个元素的功能用一个Swap()方法实现
namespace 冒泡排序
{
class Program
{
static void Main(string[] args)
{
int[] scores = new int[5];
int i, j;
int temp = 0;
int sum = 0;
//读入成绩
Console.WriteLine("请输入5个学员的成绩:");
for (i = 0; i < 5; i++)
{
Console.WriteLine("请输入第{0}个学员的成绩:",i + 1);
scores[i] = int.Parse(Console.ReadLine());
}
//开始排序---使用冒泡排序
for (i = 0; i < scores.Length - 1; i++)
{
//將最大的元素交换到最后
for (j = 0; j < scores.Length - 1 - i; j++)
{
if (scores[j] > scores[j + 1])
{
//交换元素
temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
Console.WriteLine("排序后的成绩为:");
for (j = 0; j < scores.Length; j++)
{
Console.WriteLine("{0}\t",scores[j]);
sum = sum + scores[j];
Console.WriteLine("总成绩是:{0}",sum);
}
Console.WriteLine();
}
}
}
將此程序交换数组元素的功能写一个方法来实现!