Operation of array and algorithm

Posted by phpuser_2000 on Thu, 10 Feb 2022 20:33:36 +0100

I Array definition method

Method 1

Array name= (value0 value1 value2 ...)

Method 2

Array name=([0] =value [1]=value [2]=value ... )

Method 3

List name="value0 value1 value2 ..."
Array name=($List name)

Method 4

Array name[0]="value"
Array name[1]="value"
Array name[2]="value"


☝ matters needing attention:

Ⅰ. Data types included in the array

  • value type
  • Character type
    ——Use '' or '' definitions to prevent spaces in elements from being split

Ⅱ. Get array length

ll1=(1 2 3 4 5 6 7 8 9)                
#Define array
echo $(#abc[*])perhaps echo $(#abc[@])     
#Get array length

Ⅲ. Array traversal

Ⅳ. Array slice

Divide the array and intercept the elements you want

arr=(1 2 3 4 5)
#Assign arr array elements
echo ${arr[@]}
#Output the entire array

echo ${arr[@] :0∶2}
#Get the value of ${array name [@ or *]: start position: length}

echo $ {arr[*]:1:3}

echo $ {arr[@]:2:3}

Ⅴ. Array replacement

arr=(1 2 3 4 5)

echo $ {arr[@]/4/66}      #${array name [@ or *] / find character / replace character}
echo $ {arr[@]}           #It does not replace the original contents of the array

arr=(${arr[@]/4/66})      #To change the original array, you can re assign the value
echo ${arr[@]}

Ⅵ. Delete array

arr=(1 2 3 4 5)
unset arr                  #Delete array
echo ${arr[*]}
arr=(1 2 3 4 5)
unset arr[2]               
#Delete the third element, and the subscript corresponding to the remaining elements remains unchanged after deletion
echo ${arr[*]}

Ⅶ. Array append element

① Method 1:

array _name [index]=value     #Array name [serial number] = element


② Method 2:

array _name [${#array_name[@]}]=value     #Array name [array length] = element

☞ it can be used when the subscripts are sorted normally and the corresponding elements are marked below:

☛ when the subscript element has a gap, that is, there is no space, use it with caution

③ Method 3:

array_name=("${array_name[@]} " value1 ... valueN)
#Double quotation marks cannot be omitted, otherwise, when the array array_ When there is an element containing spaces in name, the element will be divided into multiple elements according to the space. You cannot replace "" @ "with" * ". If you replace it with" * ", it will behave the same as" e "without double quotation marks. When double quotation marks are added, all elements in array _name will be added to the array as one element
for i in "$ {array_name [@]} "; do echo $i; done


④ Method 4:

array name+=(value1 ... valueN)
  • The element to be added must be surrounded by "()" and multiple elements must be separated by spaces

II Parameter transfer between function and array

2.1 passing array parameters to functions

  • If the array variable is used as a function parameter, the function will only take the first value of the array variable.
#!/bin/bash
test1(){
  echo "The parameter list received by the function is: $@"
  newarr=($1)
  echo "The value of the new array in the function is: ${newarr[@]}" 
}

arr=(30 40 20 10 50)
echo "The original array list is: ${arr[@]}"
test1 $arr

[root@centos7-1 shell]# bash shuzu1.sh 
The original array list is: 30 40 20 10 50
 The parameter list received by the function is: 30
 The value of the new array in the function is: 30

2.2 steps of transferring parameters from array to function:

  1. Now split the array into a list ${arr [*]}
  2. The function gets the list that the array was previously split into through $@$@
  3. Redefine the list as an array in the function newarr=($@0)
  4. The new array is further processed and output in echo

To solve this problem, we need to decompose the values of array variables into single values, and then use these values as function parameters. Inside the function, all parameters are recombined into a new array variable.

#!/bin/bash

test2(){
  newarr1={$@}
  length=${#newarr1[@]}
  for ((j=0;j<=$lenth-1;j++))
  do
      newarr1[$j]=$[${newarr1[$j]}*2]
  done

  echo ${newarr1[*]}
}

#######main############
array=(10 20 30 40 50)
echo "The list of the original array is: ${array[@]}"

res1=`test1 ${array[@]}`
echo "test1 The cumulative sum of the new array in is: $res1"

res2=($(test2 ${array[@]}))
echo "test2 The value of the new array in is: ${res2[@]}"

III Array sorting algorithm

3.1 bubble sorting

Similar to the action of bubble upwelling, the data will be continuously moved forward from small to large or from large to small in the array.

3.1.1 basic idea

The basic idea of bubble sorting is to compare the values of two adjacent elements. If the conditions are met, exchange the element values. Move the smaller element to the front of the array and the larger element to the back of the array (that is, exchange the positions of the two elements). In this way, the smaller element rises from the bottom to the top like an air bubble.

3.1.2 algorithm ideas

——The bubbling algorithm is realized by double-layer loop

The external loop is used to control the number of sorting rounds. Generally, the length of the array to be sorted is reduced by one time, because there is only one array element left in the last loop, and there is no need to compare. At the same time, the array has been sorted. The internal 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.

#!/bin/bash
read -p "Please enter an array list:" list
#Define an initial array
arr=($list)  #Gets the value of the first element
echo "The order of the original array is: ${arr[@]}"
#Gets the length of the array
length=${#arr[@]}

#Bubble sort:
#Define the number of comparison rounds, subtract one from the length of the array, and start from the beginning
for ((i=1;i<=$length;i++))
do
  #Determine the subscript of the element not compared, compare the two adjacent elements, put the large one back and the small one forward, and the number of comparisons in each round should decrease with the number of rounds
  for ((j=0;j<$length-$i;j++))
  do
  #Gets the value of the first element
  first=${arr[$j]}
  #Gets the value of the second element
  k=$[$j + 1]
  second=${arr[$k]}
  #Compare the values of the first element and the second element. If the first element is greater than the value of the second element, the
  if [ $first -gt $second ];then
     #First, save the value of the first element in the temporary variable temp
     temp=${arr[$j]}
     #Assign the value of the second element to the first element
     arr[$j]=$second
     #Assign the value of the original first element to the second element
     arr[$k]=$temp
  fi
  done
done

echo "After sorting, the order of the new array is: ${arr[*]}"


[root@centos7-1 shell]# bash shuzu2.sh 
Please enter an array list: 2 4 7 3 9 1
 The order of the original array is: 2 4 7 3 9 1
 The order of the new array after sorting is: 1 2 3 4 7 9

3.2 direct selection sorting

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

3.2.1 basic idea

Compare the specified sorting position with other array elements. If the conditions are met, exchange the element values. Note that the difference here is bubble sorting. Instead of exchanging adjacent elements, exchange the elements that meet the conditions with the specified sorting position (such as sorting from the last element). In this way, the sorted position will gradually expand, Finally, the entire array becomes a sorted format.

3.2.2 experiment

#!/bin/bash

arr=(30 10 40 20 50)
length=${#arr[@]}
echo "The order of the original array is ${arr[@]}"
for ((i=1;i<=$length;i++))
do
   #Let's assume that the largest element subscript is 0
   index=0
   #The subscript used to determine the actual maximum element. The comparison starts from the second element, and the subscript of the last element decreases with the number of comparison rounds
   for ((j=1;j<=$length-$i;j++))
   do
       if [ ${arr[$j]} -gt ${arr[index]} ];then
          index=$j
       fi
   done
   #After determining the subscript of the largest element of the current round, start to exchange the value of the largest element with the last element of the current round
   last=$[$length - $i]
   temp=${arr[$last]}
   arr[$last]=${arr[$index]}
   arr[$index]=$temp
done

echo "The order of the new array after sorting is: ${arr[*]}"


[root@centos7-1 shell]# bash shuzu3.sh 
The order of the original array is 30 10 40 20 50
 The new order of the array after 20 is 30

3.3 reverse sort

——Reorder the contents of the original array in reverse order.

3.3.1 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 array elements are replaced inversely.

3.3.2 experiment

#!/bin/bash

arr=(10 20 30 40 50 60 70)
length=${#arr[@]}
echo "The original array order is: ${arr[@]}"
for ((i=0;i<=$length/2;i++))
do
    temp=${arr[$i]}
    arr[$i]=${arr[$length-1-$i]}
    arr[$length-1-$i]=$temp

done

echo "The order of the sorted array is: ${arr[@]}"

[root@centos7-1 shell]# bash shuzu4.sh 
The original array order is: 10 20 30 40 50 60 70
 The order of the sorted array is 70 60 50 40 30 20 10

Topics: shell