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

I am new to C# and I am trying to study some sorting algorithm How do I make my selection sort accept negative numbers?

这是我的截图 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] + " ");
}

我想您会感到困惑,因为您对整个 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];