Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
(fix bugs and nicer implementation)
Line 1,062: Line 1,062:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm;
<lang d>import std.stdio, std.algorithm : swap;


void bubbleSort(T)(T[] data) pure nothrow {
T[] bubbleSort(T)(T[] data) pure nothrow
{
auto itemCount = data.length;
foreach_reverse (n; 0 .. data.length)
bool hasChanged = false;
{

do {
bool swapped;
hasChanged = false;
foreach (i; 0 .. n)
itemCount--;
foreach (immutable i; 0 .. itemCount)
if (data[i] > data[i + 1]) {
if (data[i] > data[i + 1]) {
swap(data[i], data[i + 1]);
swap(data[i], data[i + 1]);
hasChanged = true;
swapped = true;
}
}
} while (hasChanged);
if (!swapped)
break;
}
return data;
}
}



void main() {
void main() {
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
array.bubbleSort();
writeln(array.bubbleSort());
writeln(array);
}</lang>
}</lang>
{{out}}
{{out}}
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>



=={{header|Dart}}==
=={{header|Dart}}==