【问题标题】:Bubble sort bash script冒泡排序 bash 脚本
【发布时间】:2020-10-21 15:28:08
【问题描述】:

我正在尝试使用冒泡排序在 bash 中按字典顺序对名称列表及其分数进行排序。数组是

Ted 86
Anthony 70
Mark 95
Kyle 65
David 75

名称存储在数组names中,分数存储在数组scores中

这是我的代码,它在第 30 行给了我一个错误,说“对许多参数”,我似乎找不到原因。

#! /bin/bash
inputfile="$1"

if [[ !(-f "$1") ]]; then
    echo "$1 must be a file"
    exit 1
else
    echo "$1 is a file"
fi

names=()
scores=()

while IFS= read -r name score
do
    names+=( "$name" )
    scores+=( "$score" )
done < $inputfile
echo "The arrays before sorting"

for (( i=0; i<${#names[@]}; ++i ))
do
    echo "${names[$i]} ${scores[$i]}"
done

echo "The sorted arrays using bubble sort"
for (( i = 0; i < ${#names[@]}; i++ ))
do
    for (( j = $i; j < ${#names[@]}; j++ ))
    do
            if [ ${names[$i]} -gt ${names[$j]} ]; then #error here
                    t=${names[$i]}
                    names[$i]=${names[$j]}
                    names[$j]=$t
            fi
    done
done

for (( i=o; i<${#names[@]}; ++i ))
do
    echo "${names[$i]}"
done

谁能复制粘贴看看他们是否遇到同样的问题?

【问题讨论】:

  • 好的,我将 IFS= 替换为 IFS= " ",现在两个数组都已填充。排序相同的错误:(@KamilCuk

标签: linux bash shell command-line


【解决方案1】:

而 IFS= 读取 -r 名称分数

错了。使用 IFS= 时,不会拆分任何单词 - 整行分配给 name,而 score 始终为空。

我似乎找不到原因。

因为您将多个参数传递给 [,所以它扩展为 for ex i=0 j=1

# if [ ${names[$i]} -gt ${names[$j]} ]
# expands to:
if [ Ted 86 -gt Anthony 70 ]

没有[ 程序接收 6 个参数并且不知道如何处理它们 - 所以它退出并出现错误。当您解决上面提到的IFS 问题时 - 您仍然将 names 作为 numbers-gt 进行比较 - 我猜您的意思是按人们的 分数对他们进行排序 不是他们的名字。

【讨论】:

  • 我正在尝试对两个元素的名称和分数进行排序
猜你喜欢
  • 2013-01-24
  • 2013-10-09
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2015-03-06
  • 2018-04-18
相关资源
最近更新 更多