title: bubble sort implementation in c++
body: <p>the code below is used to implement bubble sort. why is template used in this case? and what is the purpose of <code>swapped</code> variabe. even if i remove <code>swapped</code> variable and <code>swapped condition</code> from loop code still works fine</p>
  
  <pre><code>#include &lt;algorithm&gt;
  #include &lt;iostream&gt;
  #include &lt;iterator&gt;
  
  template &lt;typename RandomAccessIterator&gt;
  void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {
    bool swapped = true;
    while (begin != end-- &amp;&amp; swapped) {
      swapped = false;
      for (auto i = begin; i != end; ++i) {
        if (*(i + 1) &lt; *i) {
          std::iter_swap(i, i + 1);
          swapped = true;
        }
      }
    }
  }
  
  int main() {
    int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
    bubble_sort(std::begin(a), std::end(a));
    copy(std::begin(a), std::end(a), std::ostream_iterator&lt;int&gt;(std::cout, " "));
    std::cout &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>ANOTHER IMPLEMENTATION:</p>
  
  <pre><code>template&lt;typename Iterator&gt;
   void bubbleSort(Iterator first, Iterator last)
   {
       Iterator i, j;
       for (i = first; i != last; i++)
           for (j = first; j &lt; i; j++)
               if (*i &lt; *j)
                   std::iter_swap(i, j); // or std::swap(*i, *j);
   }
  </code></pre>