【问题标题】:Bubble sorting associative arrays in bashbash中的冒泡排序关联数组
【发布时间】:2018-04-25 18:30:16
【问题描述】:

我需要在不使用 bash 中的速记排序的情况下对数组中的项目进行排序 从这样的数组开始

declare -A friends=(["Bob"]=22 ["Alice"]=19 ["Jane"]=21)

我必须使用键(名称)作为排序参数,按字母顺序打印数组中的项目。 预期输出

Alice 19
Bob 22
Jane 21

【问题讨论】:

  • 可以编写冒泡排序函数,但此时您将停止尝试使用bash 编写脚本并使用通用语言。跨度>
  • 到目前为止您尝试过什么?请付出一些努力,Stack Overflow 不是来做你的功课的。
  • #!/bin/bash declare -A friends=(["Bob"]=22 ["Alice"]=19 ["Jane"]=21) friendslen=${#friends[@]} function sortByName(){ for ((a=0; a<friendslen; a++)) ; do lowest=$a for ((b=a; b < friendslen; b++)) ; do if [ ${friends[b]} -le ${friends[$lowest]}] ; then lowest=$b fi done temp=${friends[a]} friends[a]=${friends[lowest]} friends[lowest]=$temp done for ((a=0; a < friendslen; a++)); do echo -e "${friends[$a]}" done echo "" } sortByName

标签: arrays bash bubble-sort


【解决方案1】:

bash 中的冒泡排序如下所示:

arr=(10 8 20 100 12) #Numbers Array

echo "Array in original order"
echo ${arr[*]}

# Performing Bubble sort 
for ((i = 0; i<5; i++))
do

    for((j = i; j<5-i-1; j++))
    do

        if ((${arr[j]} > ${arr[$((j+1))]}))
        then
            # swap
            temp = ${arr[$j]}
            arr[$j] = ${arr[$((j+1))]}  
            arr[$((j+1))] = $temp
        fi
    done
done

echo "Array in sorted order :"
echo ${arr[*]}

【讨论】:

  • 这不是有效的 bash 并且在第一行以 line 1: syntax error near unexpected token `(' 失败
  • 擅长数字排序,我需要使用名称对数组进行排序。
  • @thatotherguy 数组赋值之间的空格,是错误的原因。
  • @otherguy 空格导致错误。抱歉格式错误。
  • @AayushPathak 这仍然无效。请运行它并确保它首先工作。
猜你喜欢
  • 2012-11-14
  • 2016-02-10
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2015-03-01
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多