You need to enable JavaScript to run this app. C#入门:选择排序降序模式无法正常处理负数该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

C#入门:选择排序降序模式无法正常处理负数该如何解决?

问题根因

  • 数组遍历范围错误:你初始化了长度为1000的int数组,未输入值的元素默认值为0。排序逻辑的两层循环遍历的是整个1000长度的数组,而非你实际输入的elements个元素。降序排序时0大于所有负数,会被排到负数前面,看起来就像负数没有被正确处理。
  • 未适配排序方向选择:当前代码写死了降序的比较逻辑,没有根据用户选择的升序/降序选项做分支处理,选择升序时逻辑也不符合预期。

修复后的代码

Console.Clear();
Console.Write("Enter the number of elements: ");
int elements = Convert.ToInt32(Console.ReadLine());
// 直接根据输入的元素个数声明对应长度的数组,避免默认值干扰
int[] SelSort = new int[elements];
int num;

Console.WriteLine($"\nEnter that {elements} elements you want to put:");
for (int B = 0; B < elements; B++)
{
    SelSort[B] = Convert.ToInt32(Console.ReadLine());
}

// 输出未排序元素
Console.WriteLine("\n");
Console.Write("The Unsorted Elements are: ");
for (int S = 0; S < elements; S++)
{
    Console.Write(SelSort[S] + " ");
}

Console.WriteLine("\n");
Console.WriteLine("Would you like to sort it to the following:" +
    "\n[1] - Ascending Order" +
    "\n[2] - Descending Order\n");

Console.Write("Choose what to do on the inputed elements: ");
int selection = Convert.ToInt32(Console.ReadLine());

// 排序循环只遍历实际输入的elements个元素
for (int A = 0; A < elements - 1; A++)
{
    for (int P = A + 1; P < elements; P++)
    {
        // 根据选择的排序方向判断交换条件
        if (selection == 1) 
        {
            // 升序:前一个比后一个大就交换
            if (SelSort[A] > SelSort[P])
            {
                num = SelSort[A];
                SelSort[A] = SelSort[P];
                SelSort[P] = num;
            }
        }
        else if (selection == 2)
        {
            // 降序:前一个比后一个小就交换
            if (SelSort[A] < SelSort[P])
            {
                num = SelSort[A];
                SelSort[A] = SelSort[P];
                SelSort[P] = num;
            }
        }
    }
}

// 输出结果适配排序方向
Console.WriteLine("\n");
string sortType = selection == 1 ? "Ascending" : "Descending";
Console.Write($"Sorted Elements using Selection Sort in {sortType} Order: ");
for (int i = 0; i < elements; i++)
{
    Console.Write(SelSort[i] + " ");
}

内容的提问来源于stack exchange,提问作者iZ0N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 11:54:04