Sorting algorithms/Cocktail sort: Difference between revisions
Content added Content deleted
(Added Rust solution) |
(Added Wren) |
||
Line 3,548: | Line 3,548: | ||
Input : [-8, 15, 1, 4, -3, 20] |
Input : [-8, 15, 1, 4, -3, 20] |
||
Output : [-8, -3, 1, 4, 15, 20]</pre> |
Output : [-8, -3, 1, 4, 15, 20]</pre> |
||
=={{header|Wren}}== |
|||
{{trans|Go}} |
|||
<lang ecmascript>var cocktailSort = Fn.new { |a| |
|||
var last = a.count - 1 |
|||
while (true) { |
|||
var swapped = false |
|||
for (i in 0...last) { |
|||
if (a[i] > a[i+1]) { |
|||
var t = a[i] |
|||
a[i] = a[i+1] |
|||
a[i+1] = t |
|||
swapped = true |
|||
} |
|||
} |
|||
if (!swapped) return |
|||
swapped = false |
|||
if (last >= 1) { |
|||
for (i in last-1..0) { |
|||
if (a[i] > a[i+1]) { |
|||
var t = a[i] |
|||
a[i] = a[i+1] |
|||
a[i+1] = t |
|||
swapped = true |
|||
} |
|||
} |
|||
} |
|||
if (!swapped) return |
|||
} |
|||
} |
|||
var a = [170, 45, 75, -90, -802, 24, 2, 66] |
|||
System.print("Before: %(a)") |
|||
cocktailSort.call(a) |
|||
System.print("After : %(a)")</lang> |
|||
{{out}} |
|||
<pre> |
|||
Before: [170, 45, 75, -90, -802, 24, 2, 66] |
|||
After : [-802, -90, 2, 24, 45, 66, 75, 170] |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |