Сортировка методом вставки (Insertion sort).

В этом видео речь пойдёт о:
– алгоритмах сортиртировки;
– что такое массивы;
– как создать массив наполненный случайными данными;
– что такое сортировка методом вставки.

Скрипты использованные в видео:

Скрипт для генерации массива со случайным содержимым (числовым) для последующей сортировки.
cat 101-array_generator.sh
#!/bin/bash
clear

declare -i MAXSIZE=5
# Array declaration
i=0
while [ $i -lt $MAXSIZE ]
do
myArray[$i]=$((( RANDOM % 10 ) + 1 ))
i=$(($i+1))
done

# debug lines - print array:
i=0
while [ $i -lt $MAXSIZE ]
do
echo -n "${myArray[$i]} "
i=$(($i+1))
done
echo " "
# ===============================
# debug lines - print array one by one
i=0
while [ $i -lt $MAXSIZE ]
do
echo "myArray[$i] = ${myArray[$i]}"
i=$(($i+1))
done

# ===============================

exit 0

Скрипт осуществляющий сортировку массива методом вставки:
cat 102.1-looped-array_sorting_by_insertion.sh
#!/bin/bash
clear

while :
do

declare -i MAXSIZE=10
#Array declaration
i=0
while [[ $i -lt $MAXSIZE ]]
do
myArray[$i]=$((( RANDOM % 10 ) + 1 ))
i=$(($i+1))
done

#debug lines - print array:
i=0
while [[ $i -lt $MAXSIZE ]]
do
echo -n "${myArray[$i]} "
i=$(($i+1))
done
echo " "
#================================
#debug lines - print array one by one
i=0
while [[ $i -lt $MAXSIZE ]]
do
echo "myArray[$i] = ${myArray[$i]}"
i=$(($i+1))
done
echo " "
#================================
# Main script body.
# Declare some variables for future use:

declare -i tempValue
declare -i stopNow
declare -i count
declare -i time2stop
declare -i arrayPos=1

while [[ $arrayPos -lt $MAXSIZE ]]
do
tempValue=${myArray[$arrayPos]}
stopNow=0
count=0
time2stop=0
while [[ $time2stop -eq 0 ]]
do
if [[ $tempValue -lt ${myArray[$count]} ]]
then
j=$arrayPos
while [[ $j -gt $count ]]
do
myArray[$j]=${myArray[$(($j-1))]} #could be some issue with '$j-1'
j=$(($j-1))
# sleep 0.1
done
myArray[$count]=$tempValue
stopNow=1
i=0
while [[ $i -lt $MAXSIZE ]]
do
echo -n "myArray[$i] = ${myArray[$i]} "
i=$(($i+1))
done
echo " "
# sleep 0.1
fi
count=$(($count+1))
if [ $stopNow = 1 -o $count = $arrayPos ]
then
time2stop=1
fi
done
arrayPos=$(($arrayPos+1))
# sleep 0.1
done

i=0
echo -e "\nSorted array:"
while [[ $i -lt $MAXSIZE ]]
do
echo -n "${myArray[$i]} "
i=$(($i+1))
done
echo " "

# following done is for infinite 'while :' loop, at the beginning of the script
echo -e "\n----------------------- \n"
sleep 10
done

exit 0

Подробности в видео.
На этом всё.
Удачи!

Sources:
Глава 25. Массивы
Книга: Основы программирования для “чайников” Автор: Уоллес Вонг.