shell----------bubbling algorithm

Bubble Sort

Similar to the process of rising bubbles, the data can be moved up and down from the array to achieve sorting from largest to smallest or from smallest to largest.

Idea
This sorting is mainly to compare two adjacent numbers and move them up and down as required. If the requirement is in ascending order, then the first number will be compared with the second number. The first number is larger. It will be moved down to compare with the third number, and then analogously compared with the following values ​​to determine whether the position needs to be changed; the descending order is the opposite.

Operation process diagram:
Insert picture description here
implementation code:

#!/bin/bash
f=`cat /root/arr.txt`    					##把arr.txt文件里的数值赋给f
array=($f)
a=${#array[*]}
for ((i=1; i<$a; i++ ))					###比较轮数为数组长度减1
do
	for ((j=0; j<$a-i; j++))
        do
                if [ ${array[$j]} -gt ${array[$[$j+1]]} ];then  		###第一个数比第二个数大就进行互换
                   temp=${array[$j]}					##把第一个数赋值给temp(临时变量)
                   array[$j]=${array[$[$j+1]]}			###把第二个数赋值给第一个数
                   array[$[$j+1]]=$temp				###把temp(临时变量)赋值给第二个数
        fi
        done
done
echo ${array[*]}

Notes:

${#array[*]}					##获取当前数组位数
${array[$j]}					##第一个元素
${array[$[$j+1]]}				##第二个元素
temp							##临时变量(第1个元素的原值)

Guess you like

Origin blog.csdn.net/weixin_48190875/article/details/108123946