Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
(→‎{{header|AWK}}: Fix markup)
m (AWK example update: Customarily arrays in Awk start with index 1, not index 0)
Line 218: Line 218:
}</lang>
}</lang>


GNU awk contains built in sort() functions, but for POSIX awk,
GNU awk contains built in sort() functions, but for POSIX Awk,
here is a simple bubblesort (adapted from above). Note, it
here is a simple bubble sort (adapted from above). Note that it
is not possible to return arrays from function, so the
is not possible to return arrays from Awk functions so the
array is "edited in place". The extra parameters passed in
array is "edited in place". The extra parameters passed in
function argument lists is well known trick to use local
function's argument list is a well known trick to define local
variables.
variables.


<lang awk>
<lang awk>
# Test this example file from command line with:
#
# awk -f file.awk /dev/null
#
# Code by Jari Aalto <jari.aalto A T cante net>
# Code by Jari Aalto <jari.aalto A T cante net>
# Licensed and released under GPL-2+ http://spdx.org/licenses/
# Licensed and released under GPL-2+, see http://spdx.org/licenses


function alen(array, dummy, len) {
function alen(array, dummy, len) {
for (dummy in array)
for (dummy in array)
len++;
len++;

return len;
return len;
}
}
Line 244: Line 249:
haschanged = 0
haschanged = 0


for (i = 0; i < len - 1; i++)
for (i = 1; i <= len - 1; i++)
{
{
if ( array[i] > array[i+1] )
if (array[i] > array[i+1])
{
{
tmp = array[i]
tmp = array[i]
array[i] = array[i+1]
array[i] = array[i + 1]
array[i+1] = tmp
array[i + 1] = tmp
haschanged = 1
haschanged = 1
}
}
Line 257: Line 262:
}
}


# An Example. Sorts array to b, c, z order.
# An Example. Sorts array to order: b, c, z
{
{
array[0] = "c"
array[1] = "c"
array[1] = "z"
array[2] = "z"
array[2] = "b"
array[3] = "b"
sort(array)
sort(array)
print array[0] " " array[1] " " array[2]
print array[1] " " array[2] " " array[3]
exit
exit
}
}