Shell function and array sorting theory (with example practice notes, analysis of three sorting algorithms)

One, function overview

Function is to arrange the sequence of commands together in a format, in order to facilitate the repeated use of commands

(1) Function definition format

1.function 函数名 () {
命令序列
}

2.函数名 () {
命令序列
}

(2) Function return value

return means to exit the function and return an exit value, which can be displayed by the $? variable in the script

Principle of use:

  • The return value is taken as soon as the function ends, because the $? variable only returns the exit status code of the last command executed

  • The exit status code must be 0~255, the value will be divided by 256 if it exceeds

Example:

定义函数进行乘法运算

#!/bin/bash
db1() {
  read -p "请输入:" value
  echo $[$value * 2]
}
result=`db1`
echo $result

(3) Function parameter transfer

When defining a Shell function, you cannot take parameters, but you can pass parameters when calling the function. These passed parameters are also used in the form of $n to receive
$1 for the first parameter.
$2 for the second parameter
...
Note: $0 represents the current file name.

Example:

函数传参进行减法运算

#!/bin/bash
jian() {
    s=$[$1 - $2]
    echo $s
}
sum $1 $2

保存后执行
bash 脚本文件名 参数1 参数2

(4) Function recursion

Principle: function calls its own function

Classic case fork bomb

#!/bin/bash
.(){                ##定义函数.
.|.&		  		##递归调用本函数,&是把此程序放入后台
}
.					##运行函数.

Two, array overview

Multiple values ​​can be stored in the array. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no need to define the array size during initialization (similar to PHP).

(1) Add value to the array

方法一:
数组名=(索引0的值 索引1的值 ...)

方法二:
数组名=([0]=索引值 [1]=索引值 ...)

方法三:
列表名=“索引0的值 索引1的值 ...”
数组名=($列表名)

方法四:
数组名[0]=“索引值”
数组名[1]="索引值"
...

重复定义有则覆盖无则添加
字符使用“ ”/‘ ’定义

Variable name=${#Array name[*]/[@]}
This expression represents the length of the array

echo ${array name[*]: starting position: length}
select the range value of the length from the starting position

(2) Additional value

格式一:
数组名[索引]=数值

格式二:
数组名${#数组名[@]}]=数值

格式三:
数组名=("${数组名[@]}" 数值1 ... 数值N)
双引号不能省略,否则,当数组中存在包含空格的元素时会按空格将元素拆分成多个
不能将“@”替换为“*”,如果替换为“*”,不加双引号时与“@”的表现一致,加双引号时,会将数组中的所有元素作为一个元素添加到数组中

数组名+=(数值1 ... 数值N)
待添加元素必须用“()”包围起来,并且多个元素用空格分隔

Three, sorting algorithm

(1) Bubble sort

Basic idea:
The basic idea of ​​bubble sorting is to compare the values ​​of two adjacent elements. If the conditions are met, the element values ​​are exchanged, the smaller element is moved to the front of the array, and the larger element is moved to the back of the array (that is, exchange two The position of each element), so that the smaller element rises from the bottom to the top like a bubble.

Algorithm idea: The
bubbling algorithm is implemented by a double-layer loop, where the outer loop is used to control the number of sorting rounds. Generally, the length of the array to be sorted is reduced by one, because there is only one array element left in the last loop, and there is no need for comparison. The sorting has been completed. The inner loop is mainly used to compare the size of each adjacent element in the array to determine whether to exchange positions. The number of comparisons and exchanges decreases with the number of sorting rounds.

Example:

#!/bin/bash
array=(3 2 5 1 4)
 
for ((i=1; i<${#array[*]}; i++))                 ###比较轮数为数组长度减1,从1开始
do
  for ((j=0; j<${#array[*]}-i; j++))             ###比较相邻两个元素,较大的数往后放,比较次数随比较轮数而减少 
  
  do
    if [ ${array[$j]} -gt ${array[$[$j+1]]} ]    ###如果第一个元素比第二个元素大就互换
    then  
      temp=${array[$j]}				           	###把第一个元素值保存到临时变量中
      array[$j]=${array[$[$j+1]]}	        	###把第二个元素值保存到第一个元素中
      array[$[$j+1]]=$temp			        	###把临时变量(也就是第一个元素原值)保存到第二个元素中
    fi
  done
done

(2) Directly select and sort

Compared with bubble sorting, direct selection sorting has fewer exchanges, so it is faster

Basic idea:
Compare the specified sort position with other array elements. If the condition is met, the element value is exchanged. Note that the bubble sort is distinguished here. Instead of exchanging adjacent elements, the element that meets the condition is exchanged with the specified sort position (such as Sort from the last element), so that the sorted position gradually expands, and finally the entire array becomes the sorted format.

Example:

#!/bin/bash
su=(1 4 6 7 8 9 3 2)
ge=${#su[*]}
for ((i=1; i<$ge; i++))
do
   in=0                          
   for ((k=1; k<=$ge-i; k++))           //确定用于比较的第一个元素索引范围
   do
      if [ ${su[$in]} -lt ${su[$k]} ]   //通过比较获取最大元素的索引位置
      then
      in=$k
      fi
done
   len=$[$ge-$i]                        //获取最后一个元素的索引
   temp=${su[$len]}						//把当前轮次最后一个元素的值保存在临时变量中
   su[$len]=${su[$in]}					//把最大的元素的值赋给最后一个元素
   su[$in]=$temp						//把最后一个元素的值赋给最大元素的位置
done
echo ${su[*]}    

(3) Reverse sort

Reorder the contents of the original array in reverse order.

The basic idea:
replace the last element of the array with the first element, replace the penultimate element with the second element, and so on, until all the array elements are reversed and replaced.

Example:

#!/bin/bash
array=(10 20 30 40 50 60)
length=$(#array[*])

for ((i=0; i<$length/2; i++))
do 
  temp=${array[$i]}
  array[$i]=${array[$lengh-$i-1]}
  array[$lengh-$i-1]=$temp
done

echo ${array[*]}

Guess you like

Origin blog.csdn.net/weixin_51468875/article/details/111625425