是否可以对元素为以逗号分隔的字符串的数组进行冒泡排序?
目前我有这个:
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
文件名中的数据存储为:
text
, number
, number
.
在我的示例中,是否可以array arrList($col1,$col2,$col3)
仅按 the进行排序$col3
而不丢失$col1
和like ?$col2
答案1
您可以通过以下方式按字段 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
当然,此代码未优化并且包含重复。你可以改进它。