shell array (contains sorting algorithms)

Table of contents

One: array definition method

1. Method 1

2. Method 2

3. Method 3

4. Method 4

 5. Determine whether the array is complete

(1) Method 1

(2) Method 2: via script

Two: Get the array value

1. Get the length of the array

 2. Get the array data list

3. Obtain the list of array subscripts

4. Read a subscript assignment

5. Array traversal

 6. Find the sum of all the values ​​in the array

Three: change of array value

1. Array slicing

2. Array replacement

(1) Temporary replacement, the array will not be replaced at all

​(2) Permanent replacement needs to be reassigned

3. Array deletion --unset

4. Adding elements to the array

(1) Method 1

 (2) Method 2

(3) Method 3

(4) Method 4

 Four: Array parameter passing

1. Array parameter passing

2. Return an array from a function

 Five: Array sorting algorithm

1. Introduction to Bubble Sort

2. Bubble sort example

3. Introduction to direct selection sort

 ​4. Direct selection and sorting examples

 5. Introduction to insertion sort

6. Insertion sort example

 7. Introduction to Reverse Sort

8. Reverse sorting example

9. Sleep sequencing

10. Introduction to Hill Sorting

11. Example of Hill sort


One: array definition method

1. Method 1

数组名=(value0 value1 value2…)

 2. Method 2

数组名=([0]=value [1]=value [2]=value…)


3. Method three

数组名=“value0 value1 value2…”

数组名=($列表名)

4. Method 4

数组名[0]=“value”

 数组名[1]=“value”

数组名[2]=“value”

数组名[3]=“value”


 5. Determine whether the array is complete

Idea: Compare the last digit of the array with the last digit of the list

(1) Method 1

(2) Method 2: via script

[root@localhost ~]# vim test.sh

#!/bin/bash
a5=([0]=10 [1]=20 [3]=40 [4]=50)                  #定义数组
length=${#a5[@]}                                  #定义数组的长度
lastnum=$[length - 1]                             #定义最后一位数的下标,长度减一
lastone=${a5[$lastnum]}                           #定义下标
curlast=$(echo ${a5[@]} | awk '{print $NF}')      #定义最后一个字段

echo "a5数组的值为:${a5[@]}"

if [ $lastone -eq $curlast ];then                 #判断最后一位数值是否相等
   echo "a5数组是完整的!"                        #相等则输出完整
else
   echo "a5数组缺失元素!"                        #不相等则输出缺失
fi

 

Two: Get the array value

1. Get the length of the array

[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# echo ${#a1[@]} 
6
[root@localhost ~]# echo ${#a1[*]} 
6

 2. Get the array data list

[root@localhost ~]# echo ${a1[*]} 
10 20 30 40 50 60
[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60

3. Obtain the list of array subscripts

[root@localhost ~]# echo ${!a1[@]} 
0 1 2 3 4 5

 

4. Read a subscript assignment

[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# bl=${a1[3]}
[root@localhost ~]# echo $bl
40

 5. Array traversal

[root@localhost ~]# for i in ${a1[@]}
> do
> echo $i
> done
10
20
30
40
50
60

 6. Find the sum of all the values ​​in the array

[root@localhost ~]# for i in ${a1[@]}
> do
> sum=$[sum + i]
> done
[root@localhost ~]# echo $sum
210

Three: change of array value

1. Array slicing

[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# echo ${a1[@]:0:2}      #0为第一下标位,2为长度,2个字符
10 20
[root@localhost ~]# echo ${a1[*]:3:3}      #3为第三下表位,3为长度,3个字符
40 50 60

2. Array replacement

(1) Temporary replacement, the array will not be replaced at all

[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# echo ${a1[@]/30/100} 
10 20 100 40 50 60
[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# echo ${a1[@]/0/5} 
15 25 35 45 55 65
[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60

 (2) Permanent replacement needs to be reassigned

[root@localhost ~]# a6=(10 20 30 40 50 100)
[root@localhost ~]# echo ${a6[@]}
10 20 30 40 50 100
[root@localhost ~]# b1=${a6[@]/10/60}    #将原数组的数据替换重新赋值一个新变量 
[root@localhost ~]# echo ${b1[@]}
60 20 30 40 50 600                       #100会认为10和0,所有也会替换
 

3. Array deletion --unset

[root@localhost ~]# echo ${a1[@]} 
10 20 30 40 50 60
[root@localhost ~]# unset a1[3]                  #删除数组下标位3的数值
[root@localhost ~]# echo ${a1[@]}
10 20 30 50 60
[root@localhost ~]# unset a1                     #删除数组
[root@localhost ~]# echo ${a1[@]}

4. Adding elements to the array

(1) Method 1

格式:数组名[下标位]=元素值

[root@localhost ~]# echo ${a2[@]}
20 30 50 10 40
[root@localhost ~]# a2[5]=77
[root@localhost ~]# echo ${a2[@]}
20 30 50 10 40 77

 (2) Method 2

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

[root@localhost ~]# echo ${a2[@]}
20 30 50 10 40 77
[root@localhost ~]# a2[${#a2[@]}]=88
[root@localhost ~]# echo ${a2[@]}
20 30 50 10 40 77 88

When the array is complete, it will be appended to the last digit of the array

When the array is incomplete, the last digit will be replaced 

 (3) Method 3

格式:数组名=("${数组名[@]}" 元素值 ...) 

Note: The double quotes cannot be omitted, otherwise, when there are elements with spaces in the array, the elements will be split into multiple by spaces

You cannot replace "@" with "*". If you replace it with "*", it will behave the same as "@" without double quotes. When double quotes are added, all elements in the array will be added to the array as one element. .

when single quotes 

when double quotes

 (4) Method 4

格式:数组名+=("元素名" "元素名")

 Four: Array parameter passing

1. Array parameter passing

[root@localhost ~]# vim abc.sh

#!/bin/bash

test() {
   one=($@)
   echo "函数内的数组的元素列表为:${one[@]}"
   echo $1
   echo $2
   echo $3
   echo $4
   echo $5
}


two=(11 22 33 44 55)
echo "函数外的数组的元素列表为:${two[@]}"

test ${two[@]}

2. Return an array from a function

[root@localhost ~]# vim acc.sh

#!/bin/bash

test1() {
    one=($@)                              #函数内的数组的元素列表为${one[@]}
    for ((i=0;i<${#one[@]};i++))          #i小于${one[@]}所包含的数值个数,循环一次自加一
    do
      one[$i]=$[2 * ${one[$i]}]           #定义新的数组值为原来数组值的2倍
    done
     echo ${one[@]}
}


two=(11 22 33 44 55)
echo "函数体外的数组的元素列表为:${two[@]}"

arr=($(test1 ${two[@]}))                  #调用函数
echo "新的数组值为:${arr[@]}"

 

 Five: Array sorting algorithm

1. Introduction to Bubble Sort

Bubble sort (Bubble Sort) is a simple sorting algorithm. It iterates over the array to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of traversing the array is repeated until there is no need to exchange, that is to say, the array has been sorted. The name of this algorithm comes from the fact that the smaller elements will slowly "float" to the top of the sequence through exchange.

Running process:

Compare adjacent elements. If the first is greater than the second (in ascending order), swap them both.
Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step is done, the last element will be the largest number.
Repeat the above steps for all elements except the last one.
Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

 2. Bubble sort example

[root@localhost ~]# vim mpao.sh
#!/bin/bash
MAOPAO(){
arr=($@)
#获取数组的长度
length=${#arr[@]}

#外层循环用来定义比较轮数,比较轮数为数组长度减1,且从1开始
for ((a=1;a<length;a++));do
  #内层循环用来确定比较元素的位置,比较相邻两个元素,较大的元素往后移,并且比较次数会随着比较轮数的增加而减少
  for ((b=0;b<length-a;b++));do
    #获取相邻两个元素的前面元素的值
    first=${arr[$b]}
    #获取相邻两个元素的后面元素的值
    c=$[b + 1]
    second=${arr[$c]}
    #比较两个相邻元素的值大小,如果前面元素的值较大,则与后面元素交换位置
    if [ $first -lt $second ];then
      #使用临时变量保存前面元素的值,实现两个相邻元素交换位置
      tmp=$first
      arr[$b]=$second
      arr[$c]=$tmp
    fi
  done
done

echo "冒泡排序后的数组的值为:${arr[@]}"

}

#### main ####
read -p "请输入一组列表:" num

array=($num)
echo "旧数组的值为:${array[@]}"

MAOPAO ${array[@]}

3. Introduction to direct selection sort

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

Running process:

Compare the specified sorting position with other array elements, 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 (for example, from the last The elements start to be sorted), so that the sorted position gradually expands, and finally the entire array becomes a sorted format.

 4. Direct selection and sorting examples

[root@localhost ~]# vim zhipai.sh

#!/bin/bash

arr=(19 30 1 50 66 99)
echo "排序前的数组值为;${arr[@]}"
length=${#arr[@]}
#外层循环定义排序的轮数,为数组长度减1,且从1开始
for ((a=1;a<length;a++))
do
   #每轮比较的初始最大元素的下标,从0开始,即第一个元素
   i=0
   #内层循环定义用于与当前最大元素作比较的元素下标范围,从1开始,且每轮比较的最后一个元素下标会随着轮数增加而减少
   for ((b=1;b<=length-a;b++))
   do
     #通过比较,获取当前轮数中最大元素的下标
     if [ ${arr[$i]} -lt ${arr[$b]} ];then
        i=$b
     fi
   done
   #获取当前轮数的最后一个元素的下标
   last=$[length - a]
   #先用临时变量获取当前轮数的最后一个元素
   tmp=${arr[$last]}
   #将最大元素的值赋给当前轮数的最后一个轮数
   arr[$last]=${arr[$i]}
   #将临时变量的值,即原最后一个元素的值交换
   arr[$i]=$tmp
done
echo "排序后的数组值为:${arr[@]}"

 5. Introduction to insertion sort

Insertion Sort is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, and for unsorted data, scans from the back to the front in the sorted sequence, finds the corresponding position and inserts it. In the implementation of insertion sort, in the process of scanning from back to front, it is necessary to repeatedly shift the sorted elements backwards gradually to provide insertion space for the latest elements.

 

6. Insertion sort example

[root@localhost ~]# vim chapai.sh

#!/bin/bash

arr=(9 45 36 2 55 1 68)
echo "排序前数组值为:${arr[@]}"

length=${#arr[@]}
#外层循环定义待排序的元素下标位置
for ((a=1;a<length;a++))
do
    #内层循环定义已排好的序列的元素的元素下标位置范围
    for ((b=0;b<a;b++))
    do
       #将待排序的元素和前面已经排序好的元素依次比较,较小的数会交换到已排好序的元素位置,较大的数会放到待排序的元素位置
       if [ ${arr[$a]} -lt ${arr[$b]} ];then
         tmp=${arr[$a]}
         arr[$a]=${arr[$b]}
         arr[$b]=$tmp
       fi
    done
done
echo "排序后数组的值为:${arr[@]}"

 7. Introduction to Reverse Sort

Reorders the contents of the original array in reverse order

Running process:

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.

8. Reverse sorting example

[root@localhost ~]# vim daopai.sh

#!/bin/bash

#定义数组
arr=(0 1 2 3 4 5 6 7 8 9)
echo "排序前数组的值为:${arr[@]}"

length=${#arr[@]}

#循环减半
for ((a=0;a<length/2;a++))
do
   #获取第一个元素的值
   tmp=${arr[$a]}
   #获取当前轮数的最后一个元素下标,会随着轮数的增加而减少
   last=$[length-1-a]
   #替换最后一个元素
   arr[$a]=${arr[$last]}
   arr[$last]=$tmp
done

echo "排序后数组的值:${arr[@]}"

9. Sleep sequencing

Its principle is to sort a set of numbers in ascending order. What's special about this algorithm is that it doesn't use any compare or swap operations, but instead takes advantage of the computer's multithreading and sleep functions. Sort by the sleep time of the data in the background, the sleep time of the small value is short, and the sleep time of the large value is long.

[root@localhost ~]# vim shuimian.sh

#!/bin/bash

go() {
    sleep `echo $1*0.01 | bc`             #通过bc,进行浮点运算
    echo $1
}
a=(6 9 2 5 3 78 99)
echo "初始数组值为:${a[@]}"
for i in ${a[@]};do
   go $i &
done
sleep 1

10. Introduction to Hill Sorting

Shell sort (Shell Sort) is a type of insertion sort. Also known as shrinking incremental sorting, it is a more efficient and improved version of the direct insertion sorting algorithm. Hill sort is an unstable sorting algorithm. This method is due to DL. Shell was named after it was proposed in 1959. Hill sorting is to group records by a certain increment of the subscript, and use the direct insertion sorting algorithm to sort each group; as the increment gradually decreases, each group contains more and more keywords. When the increment is reduced to 1, The algorithm terminates when the entire file has just been grouped.

 

 

11. Example of Hill sort

[root@localhost ~]# vim xier.sh

#!/bin/bash
array=(7 6 8 3 1 5 2 4)
echo "原数组值为:${array[*]}"
length=${#array[*]}

#把距离为gap的元素编为一个组,扫描所有组,每次循环减少增量
for ((gap=$length/2; gap>0; gap/=2))
do
    for ((i=gap; i<$length; i++))
    do

          temp=${array[$i]}
          #对距离为gap的元素组进行排序,每一轮比较拿当前轮次最后一个元素与组内其他元素比较,将数组大的往后放
          for ((j=i-gap; j>=0&&temp<${array[$j]}; j-=gap))
          do
        array[$j+$gap]=${array[$j]}

          done
          #和最左边较大的元素调换位置
      array[$j+$gap]=$temp

    done
done
echo "排序后的数组值为:${array[*]}"

 

Guess you like

Origin blog.csdn.net/A1100886/article/details/130578415