2

这是我的 选择排序算法的降序输出的屏幕截图

输出

我的问题是我的代码不接受任何负数,我不知道我的 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] + " ");
}
4

1 回答 1

3

我想您会感到困惑,因为您对整个 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];
于 2021-05-11T14:03:20.087 回答