【问题标题】:I am new to C# and I am trying to study some sorting algorithm How do I make my selection sort accept negative numbers? [closed]我是 C# 新手,我正在尝试研究一些排序算法 如何让我的选择排序接受负数? [关闭]
【发布时间】:2021-08-01 21:37:51
【问题描述】:

这是我的截图 output 我的选择排序算法的降序排列

我的问题是我的代码不接受任何负数,我不知道我的 IDE 是否有问题,因为它接受升序但不降序的负数...

int[] SelSort = new int[1000];
int num;`enter code here`

Console.Clear();
Console.Write("Enter the number of elements: ");
int elements = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nEnter that " + elements + " elements you want to put:");


for (int B = 0; B < elements; B++)
{
    SelSort[B] = Convert.ToInt32(Console.ReadLine());
}

// Shows the Unsorted Elements you put in selection sort
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());

for (int A = 0; A < SelSort.Length - 1; A++)
{
    for (int P = A + 1; P < SelSort.Length; P++)
    {
        if (SelSort[A] < SelSort[P])
        {
            num = SelSort[A];
            SelSort[A] = SelSort[P];
            SelSort[P] = num;
        }
    }
}

Console.WriteLine("\n");
Console.Write("Sorted Elements using Selection Sort in Descending Order: ");
for (int i = 0; i < elements; i++)
{
    Console.Write(SelSort[i] + " ");
}

【问题讨论】:

  • 您是否考虑过使用内置排序选项?
  • int[] 存储签名号码。它怎么可能不接受负数?您是否收到某种错误消息?
  • 如果您输入例如5 个元素,数组中还有 995 个值为 0 的元素。也许这就是你所困惑的?将A &lt; SelSort.Length 替换为A &lt; elements(同样适用于P 循环)。
  • 请提供文本作为文本,而不是文本的屏幕截图。
  • 关闭这个问题的原因毫无意义。 OP 提供的代码完美地重现了他的问题,并且可以很容易地回答这个问题。因此,我投票决定重新提出问题。

标签: c# sorting negative-number selection-sort negative-integer


【解决方案1】:

我想您会感到困惑,因为您对整个 SelSort 数组进行排序,而不仅仅是您在开始时添加的“x”元素。因此,在非初始化值 0 之后(检查 SelSort[999] 值),负元素在数组末尾进行排序。

在您的情况下,您希望只对您实际使用的数组部分进行排序:

// only sort the actually used integers (< elements)
for (int A = 0; A < elements - 1; A++)
{
    for (int P = A + 1; P < elements; P++)
    {
        if (SelSort[A] < SelSort[P])
        {
            num = SelSort[A];
            SelSort[A] = SelSort[P];
            SelSort[P] = num;
        }
    }
}

甚至更好:只实例化一个元素大小的数组,而不是 1000。

Console.Clear();
Console.Write("Enter the number of elements: ");
int elements = Convert.ToInt32(Console.ReadLine());

//instantiate array with the correct number of elements
int[] SelSort = new int[elements];

【讨论】:

  • 我不明白排序算法是如何工作的以及如何在上面实现它们的循环也谢谢你的解释现在我知道如何正确实现代码了!
猜你喜欢
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 2013-04-02
  • 2018-10-13
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多