Arianule
Arianule

Reputation: 9053

Experiencing difficulty with a bubblesort exercise

I have an exercise where I need to use a WebMethod to perform a bubble sort, Ascending and Descending.

This is the method that I use for an Ascending sort for example.

[WebMethod]
public Boolean larger(int a, int b)
{
    Boolean isLarger;
    if (a < b)
    {
        isLarger = false;
    }
    else
    {
        isLarger = true;
    }
    return isLarger;
}

This is the C# application that accesses the method to perform the sort. We are required to sort 5 numbers only.

ArrayList numbersAL = new ArrayList();

for (int i = 0; i < 5; i++)
{
     numberInput = Int32.Parse(Console.ReadLine());
     numbersAL.Add(numberInput);
}
Boolean swap;

do
{
     swap = false;

     for (int j = 0; j < numbersAL.Count - 1; j++)
     {                          
          Console.WriteLine("output");
          int a = (int)numbersAL[j];
          int b = (int)numbersAL[j + 1];

          result = s.larger(a, b);

          if (result)
          {
               temporary = a;
               a = b;
               b = temporary;
               swap = true;                                           
          }                                                            
     }
} while (swap == true);

With this however I get an infinite loop and I guess the reason for this is that the numbers in the ArrayList still remains in the original order after the numbers were swapped around and then the process just repeats itself.

How could I rectify this situation.

Kind regards

Upvotes: 1

Views: 388

Answers (1)

Mike Cowan
Mike Cowan

Reputation: 919

Your swap is swapping the local variables a and b. You need to swap the corresponding numbers in numbersAL.

if (result)
{
    int temporary = (int)numbersAL[j];
    numbersAL[j] = numbersAL[j+1];
    numbersAL[j+1] = temporary;
    swap = true;                                           
}                    

Upvotes: 3

Related Questions