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 |
GNU awk contains built in sort() functions, but for POSIX Awk, |
||
here is a simple |
here is a simple bubble sort (adapted from above). Note that it |
||
is not possible to return arrays from |
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 |
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 = |
for (i = 1; i <= len - 1; i++) |
||
{ |
{ |
||
if ( |
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 |
# An Example. Sorts array to order: b, c, z |
||
{ |
{ |
||
array[ |
array[1] = "c" |
||
array[ |
array[2] = "z" |
||
array[ |
array[3] = "b" |
||
sort(array) |
sort(array) |
||
print array[ |
print array[1] " " array[2] " " array[3] |
||
exit |
exit |
||
} |
} |