Redefender - 1 month ago 12
C++ Question

why is bubble sort not working

Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?

``````//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;

bool isSorted(std::vector<int> & myData);

int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;

cin >> length;

int x = 0;

for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}

x = 1;

while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;

swap++;

}

}
pass++;

}

cout << pass << " " << swap;

return 0;
}

bool isSorted(std::vector<int> & myData)
{

for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
``````

You do not reset `x` between iterations of bubble sort. What happens is that before the first iteration of your outer loop `x` is equal to one. You then run the inner `while` loop until `x` becomes `length`, and go to the next iteration of the outer loop. By the next iteration `x` is never reset, so it still equals to `length`, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer `while` loop never breaks, and the program never finishes (and never prints anything).

To fix it, just move `x = 1` inside the loop, like this:

``````...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...
``````
Source (Stackoverflow)