Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
Line 377: | Line 377: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
<lang cpp>#include <algorithm> |
|||
{{works with|g++|4.0.2}} |
|||
#include <iostream> |
|||
#include < |
#include <iterator> |
||
// Sorts anything that provides random access iterators. |
|||
template< typename ARRAY_TYPE, typename INDEX_TYPE > |
|||
void bubble_sort( |
template <typename RAIterator> void bubble_sort(RAIterator begin, |
||
RAIterator end) { |
|||
{ |
|||
using std::swap; |
|||
bool done = false; |
|||
while (begin != end--) { |
|||
for (auto i = begin; i != end; ++i) { |
|||
⚫ | |||
⚫ | |||
swap(*i, *(i + 1)); |
|||
⚫ | |||
for (INDEX_TYPE i = 0 ; i < size-1 ; i++) |
|||
{ |
|||
if (array[i] > array[i+1]) |
|||
⚫ | |||
done = false; |
|||
std::swap(array[i], array[i+1]); |
|||
} |
|||
} |
|||
size--; |
|||
} |
} |
||
} |
|||
} |
} |
||
⚫ | |||
template< typename TYPE > |
|||
⚫ | |||
void print(TYPE val) |
|||
⚫ | |||
{ |
|||
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); |
|||
std::cout << "\n"; |
|||
} |
|||
⚫ | |||
{ |
|||
int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; |
|||
⚫ | |||
std::for_each (&array[0], &array[10], print<int>); |
|||
std::cout << std::endl; |
|||
//But in real life... |
|||
⚫ | |||
std::sort(data, data+10); |
|||
std::for_each (data, data+10, print<int>); |
|||
std::cout << std::endl; |
|||
}</lang> |
}</lang> |
||
Output: |
|||
<pre> |
|||
-199 -52 2 3 33 56 99 100 177 200 |
|||
</pre> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |