我是C#的新手,我正在尝试研究一些排序算法,如何使我的选择排序接受负数?

我是C#的新手,我正在尝试研究一些排序算法,如何使我的选择排序接受负数?,c#,sorting,negative-number,selection-sort,negative-integer,C#,Sorting,Negative Number,Selection Sort,Negative Integer,这是我的截图 我的选择排序算法的降序排序 我的问题是我的代码不接受任何负数,我不知道我的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.

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

我的问题是我的代码不接受任何负数,我不知道我的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[]SelSort=newint[1000];
int-num`在这里输入代码`
Console.Clear();
Console.Write(“输入元素数:”);
int elements=Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“\n输入要放置的“+elements+”元素:”);
for(int B=0;B
我想您可能会感到困惑,因为您对整个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;
        }
    }
}

您是否考虑过使用内置排序选项?
int[]
存储签名数字。它怎么能不接受负数呢?您是否收到某种错误消息?如果您输入例如5个元素,那么数组中还有995个值为0的元素。也许这就是你所困惑的?将
A
替换为
A
(对于P循环也是如此)。请以文本形式提供文本,而不是文本的屏幕截图。结束此问题的原因毫无意义。OP提供的代码完美地再现了他的问题,这个问题可以很容易地得到回答。因此,我投票重新开始这个问题。我不明白排序算法是如何工作的,以及如何在它上面实现循环。也感谢您的解释,现在我知道如何正确地实现代码了!
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];