0

I created a array bubble sort function for integers that works perfectly with positive integers but it crashes when negative integers are used. The initial display function works but then it just freezes. I have tried a signed int array to no avail.

I have looked all over but can't find anyone else with this exact problem.

    int defaultArray[6] = { 12, -5, 21, -1, 15, 17 };
    int numElements = 6;

    int lastSwap;
    int searchEnd = numElements - 1;
    bool sorted = false;

    while (!sorted)
    {
        for (int i = 0; i < searchEnd; ++i)
        {
            // If the number in position i is larger than the number in the
            // position i + 1 then swap them

            if (defaultArray[i] > defaultArray[i + 1]) {
                int temp = defaultArray[i];
                defaultArray[i] = defaultArray[i + 1];
                defaultArray[i + 1] = temp;
                lastSwap = i + 1;
            }
        }

        // If the lastSwap is at position one we can conclude that the array is
        // sorted so if lastSwap isn't 1 move searchEnd and continue
        if (lastSwap != 1)
        {
            // Conclude that from lastSwap to the end of the array is sorted
            // searchEnd begins one position to the left of lastSwap
            searchEnd = lastSwap - 1;
        }
        else {
            sorted = true;
        }
Ben Mukasa
  • 63
  • 10
  • 1
    You kind of forgot to describe the problem. You just say it "stops working". But what does that mean? Does it crash? Does it loop forever? Does it produce incorrect results? – David Schwartz Sep 21 '14 at 00:33
  • You don't have all your code here. Where are you initially setting `lastSwap`, and where are you setting it in your (outer) loop? – H Walters Sep 21 '14 at 00:44
  • for one thing, if your array starts out sorted, lastSwap remains undefined and so will searchEnd. – dhavenith Sep 21 '14 at 00:44

1 Answers1

1

You are trying to optimize your algorithm decreasing searchEnd, and I think that there is the problem. I recommend you to keep searchEnd the same. To determine if the array is sorted, set sorted to true and the start of the while loop and change it to false if a swap occurs. For example:

while (!sorted) {
    sorted = true;
    for (int i = 0; i < searchEnd; ++i) {
        if (defaultArray[i] > defaultArray[i + 1]) {
            // swap
            sorted = false;
        }
    }
}
rendon
  • 2,323
  • 1
  • 19
  • 25