Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -0,0 +1,37 @@
// Written in the D programming language.
module rosettaCode.sortingAlgorithms.cocktailSort;
import std.range;
Range cocktailSort(Range)(Range data)
if (isRandomAccessRange!Range && hasLvalueElements!Range) {
import std.algorithm : swap;
bool swapped = void;
void trySwap(E)(ref E lhs, ref E rhs) {
if (lhs > rhs) {
swap(lhs, rhs);
swapped = true;
}
}
if (data.length > 0) do {
swapped = false;
foreach (i; 0 .. data.length - 1)
trySwap(data[i], data[i + 1]);
if (!swapped)
break;
swapped = false;
foreach_reverse (i; 0 .. data.length - 1)
trySwap(data[i], data[i + 1]);
} while(swapped);
return data;
}
unittest {
assert (cocktailSort([3, 1, 5, 2, 4]) == [1, 2, 3, 4, 5]);
assert (cocktailSort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]);
assert (cocktailSort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]);
assert (cocktailSort((int[]).init) == []);
assert (cocktailSort(["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]) ==
["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]);
}

View file

@ -0,0 +1,7 @@
import rosettaCode.sortingAlgorithms.cocktailSort;
void main() {
import std.stdio, std.algorithm, std.range, std.random;
//generate 10 sorted random numbers in [0 .. 10)
rndGen.take(10).map!(a=>a%10).array.cocktailSort.writeln();
}

View file

@ -1,26 +0,0 @@
import std.stdio, std.algorithm;
void cocktailSort(Range)(Range data) {
bool swapped = false;
do {
foreach (i; 0 .. data.length - 1)
if (data[i] > data[i + 1]) {
swap(data[i], data[i + 1]);
swapped = true;
}
if (!swapped)
break;
swapped = false;
foreach_reverse (i; 0 .. data.length - 1)
if (data[i] > data[i + 1]) {
swap(data[i], data[i + 1]);
swapped = true;
}
} while(swapped);
}
void main() {
auto array = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
cocktailSort(array);
writeln(array);
}