-2

I'm trying to make a bubble sort. Here's what I have:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    double small;
    double big;
    double i;
    vector<double>list;
    while(cin){
        cin>>i;
        list.push_back(i);
    }
    for(i=0;i<list.size()-1;i++){
        small=list[i];
        big=list[i+1];
        if(small<=big){
        }
        else{
            list[i]=big;
            list[i+1]=small;
        }
    }
    for(i=0;i<list.size()-1;i++)
        cout<<list[i]<<'\n';
    return 0;
}

Here's my input:

123
4141
515
231366
21378
12990
5
6
8
9

but it outputs this:

123
515
4141
21378
12990
5
6
8
9        
9        
231366

The expected output should be: 5,6,8,9,123,515,4141,12990,21378,231366.(Ignore this, I was being dumb, the output is correct besides for the duplicated number). Any help? Sorry if this trivial.

Matt Wang
  • 11
  • 3

4 Answers4

0

9 is read twice since you are using while(cin), it should be

while(cin >> i){
    list.push_back(i);
}
Xiaotian Pei
  • 3,210
  • 21
  • 40
0

You are getting an extra 9 because it is the last thing you input and you are not breaking out of the loop correctly. Therefore you end up adding it to your list twice. Something like this is more appropriate:

while(cin>>i){
  list.push_back(i);
  cout << "Adding " << i << "\n";
}

In your previous cause you had the following:

while(cin){
    cin>>i; // <-- reaches the end of file
    list.push_back(i); // <-- puts something in the list even though we didn't read anything
}

Note that when cin reaches the EOF you will still add i to the list, which still has its old value as cin didn't read in any input besides EOF. The correct I have in the first code segment fixes this issue.

missimer
  • 4,022
  • 1
  • 19
  • 33
0

Your input loop is running one too many times giving a duplicate element at the end of the list. If you change the while loop to be:

 while(cin >> i){
    list.push_back(i);
 }

then the last element is only added once. You will also need to change the bounds on the output loop.

See this question about while (cin)

Community
  • 1
  • 1
Ruth Franklin
  • 365
  • 3
  • 2
0

You have to run a nested loop

for(j=0;j<list.size()-1;j++){
    for(i=0;i<list.size()-1-j;i++){

right now you are moving 231366, the biggest number, to the end of the list. You have to iterate on.

jimifiki
  • 5,377
  • 2
  • 34
  • 60