📜  使用插入排序在 Bash 中对数组进行排序

📅  最后修改于: 2022-05-13 01:57:27.110000             🧑  作者: Mango

使用插入排序在 Bash 中对数组进行排序

给定一个大小为N的数组 arr[] ,任务是使用 bash 脚本中的插入排序按升序对数组进行排序。

例子:

处理方法:按照以下步骤解决问题:



  • 在 [1, N]范围内遍历给定数组arr[ ] 并执行以下步骤:
    • 将当前元素(键)与其前一个元素进行比较。
    • 如果关键元素小于其前身,则将其与之前的元素进行比较。将较大的元素向上移动一个位置,为交换的元素腾出空间。
  • 完成上述步骤后,打印排序后的数组。

下面是上述方法的实现:

# Bash program for the above approach
n = 4
arr = (9 7 2 5)

# Perform insertion sort to sort the array
j = 1
while [ $j -lt $n ] 
do
    c = 0
    k = $(expr $j - 1)
    while [ $k -ge 0 ] 
    do
        if [ ${arr[k]} -gt ${arr[j]} ] 
        then
            c=$(expr $c + 1)
        fi
    k = $(expr $k - 1)
    done
    
    x = $j
    y = $(expr $j - 1)
    
    while [ $c -gt 0 ]
    do
        # Swapping the elements
        temp=${arr[x]}
        arr[$x]=${arr[y]}
        arr[$y]=$temp
        
        x=$(expr $x - 1)
        y=$(expr $y - 1)
        c=$(expr $c - 1)
        
    done
    
    j = $(expr $j + 1)
done

# Print the sorted array
echo "${arr[*]}"

输出: