Home c++ C++ Bubble Sort

C++ Bubble Sort

Author

Date

Category


Answer 1, authority 100%

Judging by the implementation of the algorithm, this is not bubble_sort at all, but selection sort.

With a bubble it would be

// Swap NEIGHBORING elements (changing the rest of the code as well).
swap (vArray [i], vArray [i + 1])

Answer 2, authority 29%

C++ Bubble Sort Vector

# include & lt; vector & gt;
template & lt; typename T & gt;
inline void swap (T & amp; arg1, T & amp; arg2)
{
  T temp = arg1;
  arg1 = arg2;
  arg2 = temp;
};
template & lt; typename T & gt;
void bubble_sort (std :: vector & lt; T & gt; & amp; vArray)
{
  for (int i = 0; i & lt; vArray.size (); ++ i)
  {
    for (int j = vArray.size () - 1; j & gt; i; --j)
    {
      if (vArray [i] & gt; vArray [j])
      {swap (vArray [i], vArray [j]); }
    }
  }
};

Answer 3, authority 14%

Generalized bubble sort looks like this:

template & lt; typename BidirIterator, typename Compare = std :: less & lt; & gt; & gt;
void bubble_sort (BidirIterator first, BidirIterator last, Compare cmp = {}) {
  if (first == last) return;
  while (first! = --last)
    for (auto it = first; it! = last; ++ it)
      if (! cmp (* it, * std :: next (it)))
        std :: iter_swap (it, std :: next (it));
}

The most elements “float” to the end of the sequence, so at each iteration of the outer loop, the unsorted part of the sequence is shortened from the end.

Previous articleToString C++
Next articleHow to center the picture?

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions