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}}
<lang cpp>#include <iostream>
#include <iostream>
#include <algorithm>
#include <iterator>


// Sorts anything that provides random access iterators.
template< typename ARRAY_TYPE, typename INDEX_TYPE >
void bubble_sort(ARRAY_TYPE array[], INDEX_TYPE size)
template <typename RAIterator> void bubble_sort(RAIterator begin,
RAIterator end) {
{
using std::swap;
bool done = false;
while (begin != end--) {
while ( ! done)
for (auto i = begin; i != end; ++i) {
if (*(i + 1) < *i) {
{
done = true;
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--;
}
}
}
}
}


int main() {
template< typename TYPE >
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
void print(TYPE val)
bubble_sort(std::begin(a), std::end(a));
{
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << val << " ";
std::cout << "\n";
}

int main()
{
int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
bubble_sort(array, 10);
std::for_each (&array[0], &array[10], print<int>);
std::cout << std::endl;
//But in real life...
int data[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
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#}}==