-1

I have a bit a of a problem. I'm trying to sort an array with objects in it. The objects are bottles with names, prices and types. The user makes a choice, which bottle he/she want's to add to the array.

For the assignment we have to use bubble sort. I've made it work, except it only sorts the price. The entire object doesn't switch place just the price itself. So if Coca-Cola's original price was 13 in list, after bubble sort it's 10. So the only thing that changes or gets sorted is the price and not the entire object, if that makes any sense.

public void sort_sodas()
{
    int max = sodas.Length - 1;

    for (int i = 0; i < max; i++)
    {
        int nrLeft = max - i;

        for (int j = 0; j < nrLeft; j++)
        {
            if (sodas[j+1] == null)
            {
                break;
            }
            else if (sodas[j].Price > sodas[j+1].Price)
            {
                int temp = sodas[j].Price;
                sodas[j].Price = sodas[j + 1].Price;
                sodas[j + 1].Price = temp;
            }
        }
    }

Below an image of before and after bubble sort:

enter image description here

3
  • 4
    obviously you should swap whole object not only price .. var temp = sodas[j]; sodas[j] = ... and so on Commented Mar 22, 2019 at 10:05
  • 2
    But your code only changes the Price. What type of objects are in the sodas? Can you swap whole objects instead? Commented Mar 22, 2019 at 10:06
  • I've tried to swap the entire object and not just the price. I cant make it work, if anyone could show me how it's done, I would be grateful. thank you! Commented Mar 22, 2019 at 10:09

1 Answer 1

2

You should not change prices of objects here:

else if (sodas[j].Price > sodas[j + 1].Price)
{
    int temp = sodas[j].Price;
    sodas[j].Price = sodas[j + 1].Price;
    sodas[j + 1].Price = temp;
}

You should change object positions:

else if (sodas[j].Price > sodas[j + 1].Price)
{
    var tempObject = sodas[j];
    sodas[j] = sodas[j + 1];
    sodas[j + 1] = tempObject;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!
@user11131093, you are welcome

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.