Shell script array (implement bubble sort, direct selection sort, reverse sort)


array

  • Multiple values ​​can be stored in an array (bash only supports one-dimensional arrays)
  • Array elements are indexed from 0
  • Arrays specify the values ​​of the array within parentheses, and each value can only be separated by spaces

insert image description here

Among them:
30 is index 0,
20 is index 1
, 10 is index 2,
60 is index 3
and so on, but note that the index starts from 0

如果数组中有三个参数:1 2 3
运行数组脚本后
"$*" 为 “1 2 3(作为一个整体使用)
"$@" 为“1” “2” “3” (分别作为单个的个体使用)
"$#" 为3 (表示参数的数量,也可以叫做长度)

不加双引号时与"@"的表现一致,加双引号时,会将数组arr1中的所有元素作为一个元素添加到数组中。
可以简单的理解为:用*号是作为一个整体,而用@还是单个的个体。

$*$@不加双引号时表现一致;加双引号时,$*会将所有参数作为一个整体。

array definition method

method one:

Array name = (value0 valuel value2 ...)

Example:
insert image description here

Method Two:

ArrayName = ([0]=value[1]=value[2]=value...)

Example:
insert image description here

Method three:

listname = "value0 valuel value2..."
arrayname = ($listname)

Example:
insert image description here

Method four:

array_name[0] = "value"
array_name[1] = "value"
array_name[2] = "value"

Example:
insert image description here

The data type included in the array

Value type
Character type
Use " " or ' ' to define

Get the length of the array

insert image description here

read a subscript assignment

insert image description here

array traversal

insert image description here
insert image description here

array slice

Get the value of an element in a segment of the array

Format:
${array name[@ or *]}: starting position (starting index): length
insert image description here

array replacement

permanent replacement

Format:
$(array name[@ or *]/search character/replacement character}

insert image description here

delete array

Use unset to delete the array
insert image description here
Delete the value of the element corresponding to an index in the array

insert image description here

Append elements in the array

Append some elements after the original elements in the array
insert image description here

return array from function

Call the elements of the new array to perform function operations

Addition operation

insert image description here
insert image description here

multiplication pass parameter operation

insert image description here
insert image description here

Array sorting algorithm

Bubble Sort

The action similar to the upwelling of bubbles will continuously move the data forward in the array from small to large or from large to small.

Basic idea:
The basic idea of ​​bubble sorting is to compare two adjacent element values,
exchange the element values ​​if the conditions are met, move the smaller element to the front of the array, and
move the larger element to the back of the array (that is, swap the two element positions)
so that the smaller elements rise like bubbles from the bottom to the top

Algorithm ideas:
The bubble algorithm is implemented by a double-layer loop, in which the outer loop is used to control the number of sorting rounds,
generally the length of the array to be sorted minus 1, because there is only one array element left in the last loop, no comparison is needed, and the array Already sorted. The inner loop is mainly used to compare the size of each adjacent element in the array to determine whether to exchange positions, and the number of comparisons and exchanges decreases with the number of sorting rounds.

#!/bin/bash
abc=(20 10 60 40 50 30)          #定义一个数组
echo "原数组的排列顺序为:${abc[*]}"
length=${
    
    #abc[*]}                #定义原数组的长度为length变量
for ((i=1;i<$length;i++))        #定义排序轮次
do
  for ((k=0;k<$length-i;k++))    #确定第一个元素的索引位置
  do
     first=${abc[$k]}            #定义第一个元素的值
     j=$[$k+1]                   #定义第二个元素的索引号
     second=${abc[$j]}          #定义第二个元素的值
     if [ $first -gt $second ]   #第一个元素和第二个元素比较,如果第一个元素比第二个元素大则互换
     then             
         temp=$first              #把第一个元素的值保存在临时变量temp中
         abc[$k]=$second         #把第二个元素的值赋给第一个元素
         abc[$j]=$temp           #把原第一个元素的值,赋给第二个元素
     fi
  done
done

echo "排序后数组的排列顺序为${abc[*]}"       #输出排序后的数组

insert image description here
insert image description here

direct selection sort

Compared with bubble sort, direct selection sort has fewer exchanges, so it will be faster.

Basic idea:
compare the specified sorting position with other array elements respectively, and
exchange the element values ​​if the conditions are met. Note that the difference between bubble sorting here
is not to exchange adjacent elements, but to exchange the elements that meet the conditions with the specified sorting position
(such as Sort from the last element),
so that the sorted position gradually expands, and finally the entire array becomes the sorted format.

#!/bin/bash
abc=(63 4 24 1 3 15)               #定义一个数组
echo "原数组的排列顺序为${abc[*]}" 
length=${
    
    #abc[*]}                   #定义原数组的长度,这里原数组的长度为6

for ((i=1;i<$length;i++))           #这里是定义比较的轮数,比较5次
do
  index=0                             #表示从索引0开始比较

  for ((k=1;k<=$length-i;k++))         #这里是确定用于比较的第一个元素的索引范围,比如已经定义了从索引0开始了,所以和0进行比较的范围就是从索引1-5了
   do
     first=${abc[$k]}                  #定义与index相比较的索引的取值为first
    if [ $first -gt ${abc[$index]} ]   #通过将index所在的索引的值与k所在的索引的值进行比较,获取最大元素的索引位置
    then
        index=$k
                #通过比较将较大的数定义到index中,进行下一轮的比较
    fi
       last=$[$length-$i]              #获取在比较的范围中的最后一个元素的索引
       temp=${abc[$last]}              #将上一步获取到的最后一个元素的索引的值保存到临时变量temp中
       abc[$last]=${abc[$index]}       #把最大上面for循环比较出来的最大元素的值赋值给最后一个元素
       abc[$index]=$temp               #把原来最后一个元素的值赋给原来最大值的位置的元素
   done
done

echo "排序后数组的排列顺序为${abc[*]}"   #输出排序后的数组

insert image description here
insert image description here

reverse sort

Reorders the contents of the original array in reverse order.

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

#!/bin/bash
abc=(1 23 sf 43 s 6 we 8 9)
len=${
    
    #abc[*]}
echo "原来的数组排列顺序是:${abc[*]}"
for ((i=0;i<$len/2;i++))
do
      temp=${abc[$i]}
      abc[$i]=${abc[$len-$i-1]}
      abc[$len-$i-1]=$temp
done
     echo "反转后数组的排列顺序是:${abc[*]}"

insert image description here
insert image description here

Supongo que te gusta

Origin blog.csdn.net/ll945608651/article/details/129736314
Recomendado
Clasificación