| 1 | #!/bin/bash |
| 2 | # insertion-sort.bash: Insertion sort implementation in Bash |
| 3 | # Heavy use of Bash array features: |
| 4 | #+ (string) slicing, merging, etc |
| 5 | # URL: http://www.lugmen.org.ar/~jjo/jjotip/insertion-sort.bash.d |
| 6 | #+ /insertion-sort.bash.sh |
| 7 | # |
| 8 | # Author: JuanJo Ciarlante <[email protected]> |
| 9 | # Lightly reformatted by ABS Guide author. |
| 10 | # License: GPLv2 |
| 11 | # Used in ABS Guide with author's permission (thanks!). |
| 12 | # |
| 13 | # Test with: ./insertion-sort.bash -t |
| 14 | # Or: bash insertion-sort.bash -t |
| 15 | # The following *doesn't* work: |
| 16 | # sh insertion-sort.bash -t |
| 17 | # Why not? Hint: which Bash-specific features are disabled |
| 18 | #+ when running a script by 'sh script.sh'? |
| 19 | # |
| 20 | : ${DEBUG:=0} # Debug, override with: DEBUG=1 ./scriptname . . . |
| 21 | # Parameter substitution -- set DEBUG to 0 if not previously set. |
| 22 | |
| 23 | # Global array: "list" |
| 24 | typeset -a list |
| 25 | # Load whitespace-separated numbers from stdin. |
| 26 | if [ "$1" = "-t" ]; then |
| 27 | DEBUG=1 |
| 28 | read -a list < <( od -Ad -w24 -t u2 /dev/urandom ) # Random list. |
| 29 | # ^ ^ process substition |
| 30 | else |
| 31 | read -a list |
| 32 | fi |
| 33 | numelem=${#list[*]} |
| 34 | |
| 35 | # Shows the list, marking the element whose index is $1 |
| 36 | #+ by surrounding it with the two chars passed as $2. |
| 37 | # Whole line prefixed with $3. |
| 38 | showlist() |
| 39 | { |
| 40 | echo "$3"${list[@]:0:$1} ${2:0:1}${list[$1]}${2:1:1} ${list[@]:$1+1}; |
| 41 | } |
| 42 | |
| 43 | # Loop _pivot_ -- from second element to end of list. |
| 44 | for(( i=1; i<numelem; i++ )) do |
| 45 | ((DEBUG))&&showlist i "[]" " " |
| 46 | # From current _pivot_, back to first element. |
| 47 | for(( j=i; j; j-- )) do |
| 48 | # Search for the 1st elem. less than current "pivot" . . . |
| 49 | [[ "${list[j-1]}" -le "${list[i]}" ]] && break |
| 50 | done |
| 51 | (( i==j )) && continue ## No insertion was needed for this element. |
| 52 | # . . . Move list[i] (pivot) to the left of list[j]: |
| 53 | list=(${list[@]:0:j} ${list[i]} ${list[j]}\ |
| 54 | # {0,j-1} {i} {j} |
| 55 | ${list[@]:j+1:i-(j+1)} ${list[@]:i+1}) |
| 56 | # {j+1,i-1} {i+1,last} |
| 57 | ((DEBUG))&&showlist j "<>" "*" |
| 58 | done |
| 59 | |
| 60 | |
| 61 | echo |
| 62 | echo "------" |
| 63 | echo $'Result:\n'${list[@]} |
| 64 | |
| 65 | exit $? |