Shell script-bubble sort

Overview of bubbling

Bubble sort is actually an action similar to the upsurge of bubbles, which will continuously move the data forward in the array from small to large or from large to small.

Icon reference:
Insert picture description here

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, to exchange two elements Position) so that the smaller element rises from the bottom to the top like a bubble.

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.

Command example

#!/bin/bash

SZ=(3 8 4 6 7 5 2 1)
a=$[ ${#SZ[*]} ]
for ((i=1; i<$a; i++))                    #######比较轮数为数组长度减一,从1开始
do
   for ((b=0; b<$a-i; b++))            #######比较相邻两个元素,较大的数往后放,比较次数随比较轮数而减少
do
if [ ${SZ[$b]} -lt ${SZ[$[$b+1]]} ];then            ###如果第一个元素比第二个元素大就互换
  jap=${SZ[$b]}                                        ######把第一个元素值保存到临时变量中
  SZ[$b]=${SZ[$[$b+1]]}                      ######把第二个元素值保存到第一个元素中
  SZ[$[$b+1]]=$jap                                #########把临时变量(也就是第一个元素值)保存到第二个元素中
fi
done
done
echo "${SZ[*]}"

Command picture shows: (for: pay attention to spaces and operation effects)
Insert picture description here
show picture:
Insert picture description here
############################# #Reverse
order:
Insert picture description here
display icon:
Insert picture description here

————————————————————————————————————————

It ends here…

Thanks for watching... if you like it, give a thumbs up

Guess you like

Origin blog.csdn.net/XCsuperman/article/details/108100344