文字列を含むバブルソート配列

文字列を含むバブルソート配列

要素がコンマで区切られた文字列である配列をバブルソートできますか?

現在私はこれを持っています:

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)だけでソートできますか?$col3$col1$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

もちろん、このコードは最適化されておらず、重複した内容が含まれています。改善できます。

おすすめ記事