Sorting Algorithm
One, bubble sort
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
1.1 Basic idea
The basic idea of bubble sorting is to compare the values of two adjacent elements, 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, the exchange of two elements Position) so that the smaller element rises from the bottom to the top like a bubble.
1.2 Algorithm ideas
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 minus 1 time, because there is only one array element left in the last loop, no comparison is needed, and the array has been sorted Up. 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.
1.3 Example
arr=(54 3 1233 -4 135 31 1)
echo "原数组为:${arr[*]}"
length=${#arr[*]}
for ((a=1;a<$length;a++))
do
for ((b=0;b<$length-a;b++))
do
if [ ${arr[$b]} -gt ${arr[$[$b+1]]} ]
then
temp=${arr[$b]}
arr[$b]=${arr[$[$b+1]]}
arr[$[$b+1]]=$temp
fi
done
done
echo "新数组为:${arr[*]}"
Second, select and sort directly
Compared with bubble sort, direct selection sort has fewer exchanges, so it is faster
2.1 Basic idea
Compare the specified sort position with other array elements. If the condition is met, the element value will be exchanged. Note that the difference is bubble sorting. Instead of exchanging adjacent elements, the element that meets the condition is exchanged with the specified sort position (such as from the last The elements begin to be sorted), so that the sorted position gradually expands, and finally the entire array becomes the sorted format.
2.2 Example
arr=(25 31 2 45 123 312 4)
echo "原数组为:${arr[*]}"
length=${#arr[*]}
for ((a=1;a<$length;a++))
do
index=0
for ((b=1;b<=$length-a;b++))
do
if [ ${arr[$b]} -gt ${arr[$index]} ];then
index=$b
fi
done
temp=${arr[$length-$a]}
arr[$length-$a]=${arr[$index]}
arr[$index]=$temp
done
echo "新数组为:${arr[*]}"
Three, reverse sort
Reorder the contents of the original array in reverse order
3.1 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
3.2 Example
arr=(10 20 30 40 50 60)
echo "原数组为:${arr[*]}"
length=${#arr[*]}
for ((a=0; a<$length/2; a++))
do
temp=${arr[$a]}
arr[$a]=${arr[$lenqth-$a-1]}
arr[$length-$a-1]=$temp
done
echo "新数组为:${arr[*]}"