包含字符串的冒泡排序数组

醉汉

是否可以对包含以字符串形式的元素(用逗号分隔)的数组进行冒泡排序?

目前,我有这个:

lines=$(wc -l filename.txt | awk '{ print $1 }')
while IFS=, read -r col1 col2 col3
do
#echo "$col1 , $col2, $col3"
arr+=($col3)
arrOrig+=($col3)
arrList+=($col1,$col2,$col3) 
done < filename.txt
echo "Array in original order"
echo ${arr[*]}  
 #Performing Bubble sort  
for ((i = 0; i<$lines; i++)) 
do     
for ((j = i; j<$lines-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

在文件名数据被存储为:textnumbernumber

是否可以array arrList($col1,$col2,$col3)仅按进行排序$col3而不会丢失$col1$col2像我的示例一样?

尤里·贡查鲁克(Yurij Goncharuk)

您可以按以下方式按字段3进行冒泡排序:

#!/bin/bash
while IFS=, read -r col1 col2 col3
do
    arr+=("$col1, $col2, $col3")
done < tel.txt

echo "Array in original order: "
for i in "${arr[@]}"
do
    echo "$i "field3=`echo $i | cut -d ',' -f 3`
done

lines=`cat tel.txt | wc -l`

#Performing Bubble sort
for ((i = 0; i<$lines; i++))
do
    for ((j = i; j<$lines-i-1; j++))
    do
        if (( `echo ${arr[j]} | cut -d ',' -f 3` > `echo ${arr[$((j+1))]} | cut -d ',' -f 3` ))
        then
                #swap
                temp=${arr[$j]}
                arr[$j]=${arr[$((j+1))]}
                arr[$((j+1))]=$temp
            fi
    done
done

echo "Array in sorted order: "
for i in "${arr[@]}"
do
    echo "$i "
done

tel.txt包含以下字符串:

yurijs-MacBook-Pro:bash yurij$ cat tel.txt
Some text1, 45, 23
Some test2, 12, 3
Some text3, 33, 99
Some test4, 56, 22
Some text5, 22, 65

运行buuble_sort.sh

yurijs-MacBook-Pro:bash yurij$ ./buuble_sort.sh
Array in original order:
Some text1,  45,  23 field3= 23
Some test2,  12,  3 field3= 3
Some text3,  33,  99 field3= 99
Some test4,  56,  22 field3= 22
Some text5,  22,  65 field3= 65
Array in sorted order:
Some test2,  12,  3
Some test4,  56,  22
Some text1,  45,  23
Some text5,  22,  65
Some text3,  33,  99

原因是此代码未经过优化,并且包含重复。您可以改善它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章