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