Search code examples
c#sortingnegative-numberselection-sortnegative-integer

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


Here is my Screenshot of the output of the descending order for my selection sorting algorithm

output

My problem is my code doesn't accept any negative numbers and I don't know if my IDE is at fault because it accepts negative numbers in ascending but not descending...

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] + " ");
}

Solution

  • I suppose you get confused because you sort the whole array of SelSort instead of just the 'x' elements you added at the start. So the negative elements get sorted in the end of the array after the non-intialised values of 0 (check SelSort[999] value).

    In your case you would prefer sorting only the part of the array you are actually using:

    // 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;
            }
        }
    }
    

    Or even better: only instantiate an array of the size of your elements instead of 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];