我想同時對 2 個陣列進行排序。陣列如下:wordArray和numArray。兩者都是全球性的。
這 2 個陣列包含文本檔案中的所有單詞(沒有重復)和每個單詞的出現次數。
現在我正在使用冒泡排序同時對它們進行排序:
# Bubble Sort function
function bubble_sort {
local max=${#numArray[@]}
size=${#numArray[@]}
while ((max > 0))
do
local i=0
while ((i < max))
do
if [ "$i" != "$(($size-1))" ]
then
if [ ${numArray[$i]} \< ${numArray[$((i 1))]} ]
then
local temp=${numArray[$i]}
numArray[$i]=${numArray[$((i 1))]}
numArray[$((i 1))]=$temp
local temp2=${wordArray[$i]}
wordArray[$i]=${wordArray[$((i 1))]}
wordArray[$((i 1))]=$temp2
fi
fi
((i = 1))
done
((max -= 1))
done
}
#Calling Bubble Sort function
bubble_sort "${numArray[@]}" "${wordArray[@]}"
但是由于某種原因,當大型陣列就位時,它不會正確排序它們。
有誰知道它有什么問題或其他方法來對具有或不具有陣列的相應出現次數的單詞進行排序?
這個:
wordArray = (because, maybe, why, the)
numArray = (5, 12, 20, 13)
必須轉向這個:
wordArray = (why, the, maybe, because)
numArray = (20, 13, 12, 5)
有人建議將兩個陣列并排寫在一個文本檔案中,然后對檔案進行排序。
它將如何用于此輸入:
1 Arthur
21 Zebra
轉到此輸出:
21 Zebra
1 Arthur
uj5u.com熱心網友回復:
假設陣列不包含制表符或換行符,如何:
#!/bin/bash
wordArray=(why the maybe because)
numArray=(20 13 12 5)
tmp1=$(mktemp tmp.XXXXXX) # file to be sorted
tmp2=$(mktemp tmp.XXXXXX) # sorted result
for (( i = 0; i < ${#wordArray[@]}; i )); do
echo "${numArray[i]}"$'\t'"${wordArray[i]}" # write the number and word delimited by a tab character
done > "$tmp1"
sort -nrk1,1 "$tmp1" > "$tmp2" # sort the file by number in descending order
while IFS=$'\t' read -r num word; do # read the lines splitting by the tab character
numArray_sorted =("$num") # add the number to the array
wordArray_sorted =("$word") # add the word to the array
done < "$tmp2"
rm -- "$tmp1" # unlink the temp file
rm -- "$tmp2" # same as above
echo "${wordArray_sorted[@]}" # same as above
echo "${numArray_sorted[@]}" # see the result
輸出:
why the maybe because
20 13 12 5
如果您不想創建臨時檔案,這里是這個process substitution版本,它可以在不寫入/讀取臨時檔案的情況下運行得更快。
#!/bin/bash
wordArray=(why the maybe because)
numArray=(20 13 12 5)
while IFS=$'\t' read -r num word; do
numArray_sorted =("$num")
wordArray_sorted =("$word")
done < <(
sort -nrk1,1 < <(
for (( i = 0; i < ${#wordArray[@]}; i )); do
echo "${numArray[i]}"$'\t'"${wordArray[i]}"
done
)
)
echo "${wordArray_sorted[@]}"
echo "${numArray_sorted[@]}"
或者更簡單(使用 KamilCuk 的建議):
#!/bin/bash
wordArray=(why the maybe because)
numArray=(20 13 12 5)
while IFS=$'\t' read -r num word; do
numArray_sorted =("$num")
wordArray_sorted =("$word")
done < <(
paste <(printf "%s\n" "${numArray[@]}") <(printf "%s\n" "${wordArray[@]}") | sort -nrk1,1
)
echo "${wordArray_sorted[@]}"
echo "${numArray_sorted[@]}"
uj5u.com熱心網友回復:
您需要對數字進行數字排序。您可以像這樣對陣列進行排序:
mapfile -t wordArray <(printf '%s\n' "${wordArray[@]}" | sort -n)
但你真正需要的是:
for num in "${numArray[@]}"; do
echo "$num: ${wordArray[j ]}"
done |
sort -n k1,1
但是,在此程序的早期,您應該只使用一個陣列,其中單詞和頻率(反之亦然)是鍵值對。那么他們總是有直接的關系,可以像上面的for回圈一樣列印出來。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358777.html
標籤:猛击
