C#中冒泡排序问题.?

2025-04-27 22:51:28
推荐回答(5个)
回答1:

参考:
///


/// 下面这个程序演示使用二重循环实现冒泡排序!
///

class Program
{
static void Main(string[] args)
{
int i, j,temp;
int[]answer=new int[5]; //成绩数组
Console.WriteLine("请你输入5个学生的成绩:\n"); //读入成绩
for (i = 0; i < 5;i++ )
{
Console.WriteLine("请输入第{0}个学生的成绩:\n",i+1);
answer[i] = int.Parse(Console.ReadLine()); //把字符串转换成整型
}
//开始排序--使用冒泡排序
for (i = 0; i < answer.Length - 1;i++ ) //比较多少轮
{
//将最大的数交换到最后
for (j = 0; j < answer.Length - 1-i;j++ )
{
if(answer[j]{
//交换元素
temp=answer[j];
answer[j]=answer[j+1];
answer[j + 1] = temp;
}
}
}
//排序后输出
Console.WriteLine("排列后的成绩为:");
for (i = 0; i < answer.Length;i++ )
{
Console.Write("{0}\t",answer[i]);
}
}
}

回答2:

static void Main(string[] args)
{
int[] arr = {44,4,1, 2, 3, 8, 5};
Sort(arr);
for (int k = 0; k < arr.Length; k++)
{
Console.WriteLine(arr[k]);
}
}

//排序
public static void Sort(int[] intArray)
{
for (int j = 1; j < intArray.Length; j++)
{
for (int i = 0; i < intArray.Length-1; i++)
{
//把最大值往后移动
if (intArray[i] >intArray[i + 1])
{
int Max = intArray[i];
intArray[i] = intArray[i + 1];
intArray[i + 1] = Max;
}
}
}
}

回答3:

两两对比。小的排前。
例如
3,1,5
3,1对比1排前。整个为1,3,5. OK了
如果是
5,3,1
5,3对比。3排前。成351.35正常符合要求。51不符合。在排前唱315.(呵呵)
31有不符合。排13.整体为135 OK了,呵呵具体代码有人写了,可以用。我只是说的白话点

回答4:

namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
int temp;
int[] tic = new int[10];
Console.WriteLine("请输入超级女生北京赛区前10强的参赛者");
for (int i = 0; i < tic.Length; i++)
{
Console.WriteLine("请输入第{0}个参赛者的票数", i + 1);
tic[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < tic.Length - 1; i++)
{
for (int j = 0; j < tic.Length - 1 - i; j++)
{

if (tic[j] > tic[j + 1])
{

temp = tic[j];
tic[j] = tic[j + 1];
tic[j + 1] = temp;
}
}
}

Console.WriteLine("排序后的票数为");
for (int i = 0; i < tic.Length; i++)
{
Console.Write("{0}\t", tic[i]);
}
Console.ReadLine();
}
}
}

回答5:

由于用的手机,我简单说一下思想。对一数组里的数排序,用循环命令进行两两对比,小的数令其排前。对有n个数的数组最多进行n-1次排序就保证从小到大排列。这很像让小的数像气泡一样浮起来,所以叫冒泡排序