-3

Right now I'm trying to learn Bubble sorting, but I'm having an issue where the while loop I'm using loops 1 to few times. I think that the problem is inside the loop that sets the bool "done" to true, but I have not been able to fix the issue.

Here is a pastebin link to the code: https://pastebin.com/7QRTm1ju

here is the loop in question:

//checking if string is in order (low to high)
for (int x = 0; x < sizeof(yeet) / sizeof(yeet[0]); x++)
{
    if (yeet[x] < yeet[x + 1])
    {
        length++;
        if (length == stop)
        {
            done = true;
        }

    }
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • 8
    It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – NathanOliver Oct 12 '18 at 18:52
  • I would enter your code into http://pythontutor.com/ so that you can view it line by line to see where the error is. SO is not a homework help website :( – Arya Oct 12 '18 at 18:53
  • 1
    Possible duplicate of [Bubble Sort Homework](https://stackoverflow.com/questions/895371/bubble-sort-homework) – Arya Oct 12 '18 at 18:55
  • 2
    Avoid linking to code. Links rot, and when the information at the link is important to the question, the question is rendered useless. Prefer to contain in the question a [mcve]. – user4581301 Oct 12 '18 at 18:57

1 Answers1

0

The code is looping one too many times, not one too few. Use this instead:

//checking if string is in order (low to high)
int n = sizeof(yeet) / sizeof(yeet[0]);
for (int x = 0; x < n - 1; x++)
{
    if (yeet[x] < yeet[x + 1])
    {
        length++;
        if (length == stop)
        {
            done = true;
        }

    }
}

When x is equal to n-1, if you read from yeet[x + 1] you go beyond the end of the array. Remember, for an array of n elements, a valid array index is from 0 to n-1 inclusive.

You may want to review the code you're using to calculate the value of stop, and other loops in your program.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39