Array and sorting algorithm
- 1. Array definition method
- Two, the data types included in the array
- Three, get the length of the array and get the data list
- Four, array traversal
- Five, array slicing
- Six, array replacement
- Five, array deletion
- Six, add elements to the array
- Seven, pass array parameters to the function
- Eight, the function passes parameters to the array
- Nine, array sorting algorithm
1. Array definition method
Element value: (30 20 10 60 50 40)
Index: 0 1 2 3 4 5
Four methods
1.method one
Array name=(value0 value1 value2 …)
2.Method Two
Array name=([0]=value [1]=value [2]=value …)
3.Method Three
List name = "value0 value1 value2 …"
Array name = ($list name)
4.Method Four
Array name [0] = "value"
Array name [1] = "value"
Array name [2] = "value"
Two, the data types included in the array
- 数值类型
- 字符类型(字符串):使用" "或' '定义,防止元素当中有空格,元素按空格分割
Three, get the length of the array and get the data list
Get the length of the array
array=(1 2 3 4 5 6 7 8) ///定义数组
echo ${#array[*]}或者 echo ${#array[@]} ///获取数组长度
Get data list
echo ${array[*]}或者 echo ${array[@]}///区别@加引号时数据每个是单个主体 *号是一个整体
Read an index assignment
echo ${array[索引号]}
Four, array traversal
#!/bin/bash
arr1=(1 2 3 4 5)
for i in ${arr1[@]}
do
echo $i
done
Five, array slicing
array=(1 2 3 4 5 6)
echo ${array[@]} ///输出整个数组,此处*与@相同
echo ${array[@]:0:2} ///获取 ${数组名[@或*]:起始位置:长度} 的值
echo ${array[*]:1:3}
echo ${array[*]:2:3}
Six, array replacement
Method 1: Single replacement
array=(1 2 3 4 5 6)
echo ${array[@]}
array[0]=66
echo ${array[@]}
Method 2: Multiple replacement temporary replacement (will not change the data of the original array)
array=(1 2 3 4 5)
echo ${array[@]/4/66} ///$(数组名[@或*]/查找字符(替换字符)
echo ${
array[@]} ///并会替换数组原有的数据
array=($array[@]/4/66)
echo ${array[@]}
Five, array deletion
array=(1 2 3 4 5 6)
unset array #删除数组
echo ${array[@]}
array=(1 2 3 4 5 6)
unset array[2] #删除第三个元素
echo ${array[*]}
Six, add elements to the array
method one:
array=(1 2 3 4 5 6)
array[6]=7 ///在最后一个索引号添加比最后一个索引大的索引 在加上元素
array[7]=80
Method Two:
array[${#array[@]}]=7 ///根据数组长度添加索引添加元素,如果数组索引不是连续的则无法生效
Method three:
array=("${array[@]}" 1 2 3 4 5)
Double quotation marks cannot be omitted, otherwise, when there are elements in the array that contain spaces, the elements will be split into multiple by spaces. You cannot replace "@" with " ". If you replace it with" , " it will be combined with "@" if you do not add double quotation marks. "" behaves the same, when double quotation marks are added, all the elements in the array will be added to the array as an element
for i in "${array[@]}"; do echo $i; done
Method four:
array+=(10 20 30...)
#带添加元素必须使用()包围起来,并且多个元素用空格分割
Seven, pass array parameters to the function
If an array variable is used as a function parameter, the function will only take the first value of the array variable
#/bin/bash
test1() {
echo "接收到的数据为:$@"
newarr=($1)
echo "新数组的数据:${newarr[*]}"
}
arr=(1 2 3 4 5 6)
echo "arr数组的数据: ${arr[*]}"
test1 $arr
To solve this problem, you need to decompose the values of the array variables into individual values, and then use these values as function parameters. Inside the function, recombine all the parameters into a new array variable
#/bin/bash
test2() {
echo "接收到的数据为:$@"
newarr=($@)
echo "新数组的数据:${newarr[*]}"
}
arr=(1 2 3 4 5 6)
echo "arr数组的数据: ${arr[*]}"
test2 ${arr[@]}
Eight, the function passes parameters to the array
Example 1:
#/bin/bash
test3() {
newarray=($@)
sum=0
for i in ${newarray[@]}
do
sum=$[$sum+$i]
done
echo $sum
}
array=(1 2 3 4 5 6)
echo "初始array数组的值 ${array[@]}"
result=`test3 ${
array[@]}`
echo "数组的和 $result"
Example 2
#/bin/bash
test(){
newarray=($@)
for ((i=0; i<${#newarray[@]}; i++))
do
newarray[$i]=$[${newarray[$i]} * 2]
done
echo ${newarray[@]}
}
array=(1 2 3 4 5 6)
echo "初始数组数据 ${array[@]}"
result=(`test ${
array[@]}`)
echo "新数组 ${result[@]}"
Nine, array sorting algorithm
(1) Bubble sorting algorithm
Similar to the upsurge of bubbles, the data will continue to move forward in the array from small to large or from large to small.
2. The 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 move the larger element to the back of the array (that is, Swap the positions of the two elements) so that the smaller element rises from the bottom to the top like a bubble.
3. Algorithm idea: The bubbling algorithm is implemented by a double 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 time, because there is only one array element left in the last loop, no comparison is required. At the same time the array has been sorted. 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.
#!/bin/bash
read -p "输入需要排序的数组:" x
array=($x)
echo "旧数组为:${array[@]}"
#获取数组长度
length=${#array[@]}
for ((i=1;i<$length;i++))
do
#确定数值位置,大的往后放,并且比较次数随着轮数增加而减少
for ((a=0;a<$length-$i;a++))
do
#定义第一个和第二个比较的数值
first=${array[$a]}
second=${array[$a+1]}
if [ $first -gt $second ];then
#把第一个数值赋予给一个临时变量temp
temp=${array[$a]}
#把第二个数值赋予给第一个数值
array[$a]=${array[$a+1]}
#再把第一个数值的值(临时变量temp)赋予给第二个数值
array[$a+1]=$temp
fi
done
done
echo "排序后的数组顺序为:${array[@]}"
(2) Directly select and sort
1. Direct selection sorting
Compared with bubble sorting, direct selection sorting has fewer exchanges, so it is faster.
2. Basic idea: Compare the specified sorting position with other array elements respectively. If the condition is met, the element value is exchanged. 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, start sorting from the last element), so that the sorted position gradually expands, and finally the entire array becomes the sorted format
#!/bin/bash
arr=(20 30 10 60 40 50)
echo "原数组的值为:${arr[@]}"
length=${#arr[@]}
#定义排序轮数
for ((a=1;a<$length;a++))
do
#假设索引为0的元素是最大的
index=0
#定义和第一个元素比较的索引,来确定最大的元素索引
for ((b=1;b<=$length-$a;b++))
do
#定义最大的元素的值
max=${arr[$index]}
#定义从索引1开始比较的元素的值
element=${arr[$b]}
#判断如果从索引1开始比较的元素的值大于当前最大元素的值,就记录最大值的索引到index
if [ $element -gt $max ];then
index=$b
fi
done
#定义每一轮比较的最后一个元素的索引
last=$[$length-$a]
#把当前轮次的最后一个元素的值赋给临时变量temp
temp=${arr[$last]}
#把最大的值赋给当前轮次的最后一个元素
arr[$last]=${arr[$index]}
#把temp里的原来最后一个元素的值赋给原最大值所在索引的元素
arr[$index]=$temp
done
echo "排序后的数组为:${arr[@]}"
(3) Reverse display
1. Reorder the contents of the original array in reverse order
2. Basic idea:
Replace the last element of the array with the first element. The penultimate element is replaced with the second element, and so on, until all the array elements are reversed and replaced
#!/bin/bash
arr=(1 2 3 4 5)
length=${#arr[@]}
for ((i=0;i<$length/2;i++))
do
temp=${arr[$i]}
arr[$i]=${arr[$length-$i-1]}
arr[$length-$i-1]=$temp
done
echo ${arr[@]}