Christopher K. Christopher K. - 2 months ago 12
C++ Question

Bubble sort algorithm issue in C++

My math assignment requires me to develop a few forms of sorting algorithms, and I decided to start off with an "easy" one: the bubble sort.

I have two lists:

3.3 5 9.89 -6


and

-564 1340 42 129 858 1491 1508 246 -1281 655 1506 306 290 -768 116 765 -48 -512 2598 42 2339


I'm able to sort the first one easily, but have an issue mid-sorting for the second one.

Here is my small chunk of code that takes care of the sorting.

int bubbleSort(std::list<double> list)
{
std::list<double>::iterator it; // First iterator i
std::list<double>::iterator it2; // Second iterator i+1
int comp = 0;

it = list.begin();
it2 = list.begin();
it2++;
for (int i = list.size() - 1; i > 0; --i)
{
for (int j = 0; j < i; j++)
{
comp++;
if (*it2 < *it) // If my second item is smaller than my first one, swap them
{
std::swap(*it2, *it);
it = list.begin();
it2 = list.begin();
it2++;
break;
}
it++;
it2++;
}
}
return comp;
}


Here is the outputed list I get, as you can see it stops being sorted mid way:

-1281 -564 42 129 246 858 1340 1491 655 1508 1506 306 290 -768 116 765 -48 -512 2598 42 2339


Where did I go wrong in my algorithm?

dd2 dd2
Answer

This is the working code for bubble sort you might be looking.

  1. First you have to pass the list by ref not value
  2. Bubble up the maximum value at the end of the list.
  3. Properly initialize the it,it2 inside first for loop.

    #include <bits/stdc++.h>
    using namespace std;
    
    int bubbleSort(std::list<double> &list) {
     std::list<double>::iterator   it; // First iterator i
     std::list<double>::iterator   it2; // Second iterator i+1
     int                           comp = 0;
    
     for (int i = list.size() - 1; i > 0; --i) {
       it = list.begin();
       it2 = list.begin();
    
       it2++;
       for (int j = 0; j < i; j++) {
         comp++;
         if (*it2 < *it) { // If my second item is smaller than my first one, swap them
           std::swap(*it2, *it);
           //it = list.begin();
           //it2 = list.begin();
           //it2++;
           //break;
         }
         it++;
         it2++;
       }
     }
     return comp;
    }
    
    int main() {
     list<double> l;
     int n;
     cin >> n;
     while (n--) {
       double tmp;
       cin >> tmp;
       l.push_back(tmp);
     }
     bubbleSort(l);
     for (list<double>::iterator i = l.begin(); i != l.end(); i++) {
       cout << *i << " ";
     }
     cout << endl;
    }
    
Comments