Sorting algorithms/Bubble sort: Difference between revisions

m
AWK example update: Customarily arrays in Awk start with index 1, not index 0
(→‎{{header|AWK}}: Fix markup)
m (AWK example update: Customarily arrays in Awk start with index 1, not index 0)
Line 218:
}</lang>
 
GNU awk contains built in sort() functions, but for POSIX awkAwk,
here is a simple bubblesortbubble sort (adapted from above). Note, that it
is not possible to return arrays from function,Awk functions so the
array is "edited in place". The extra parameters passed in
function's argument listslist is a well known trick to usedefine local
variables.
 
<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>
# Licensed and released under GPL-2+, see http://spdx.org/licenses/
 
function alen(array, dummy, len) {
for (dummy in array)
len++;
 
return len;
}
Line 244 ⟶ 249:
haschanged = 0
 
for (i = 01; i <= len - 1; i++)
{
if ( array[i] > array[i+1] )
{
tmp = array[i]
array[i] = array[i + 1]
array[i + 1] = tmp
haschanged = 1
}
Line 257 ⟶ 262:
}
 
# An Example. Sorts array to order: b, c, z order.
{
array[01] = "c"
array[12] = "z"
array[23] = "b"
sort(array)
print array[01] " " array[12] " " array[23]
exit
}
Anonymous user