Bash快速排序函数未更新全局数组问题求助
问题分析与修复
你的快速排序代码未生效的核心原因是使用了HTML转义字符<和>代替Bash的比较运算符<和>,导致循环条件始终不成立,数组元素从未被交换,最终返回原数组。
错误点详解
在partition函数的两个while循环中:
while ((arr[i] < pivot && i <= high)); do # 以及 while ((arr[j] > pivot && j >= 0)); do
<、>是HTML语境下的转义字符,Bash无法将其识别为比较运算符,这两个循环会直接跳过执行。i和j仅完成一次自增/自减就进入交换判断,此时两者的位置不符合交换条件,最终分区函数返回的j值无法正确分割数组,排序逻辑完全失效。
另外还有一个优化点:j的下限应该是low而非0,因为当前分区仅处理[low, high]区间的元素,无需考虑数组的前半部分。
修正后的代码
#!/usr/bin/bash arr=(1 8 3 9 4 5 7 2) partition() { local low=$1 local high=$2 local pivot=${arr[low]} local i=$((low - 1)) local j=$((high + 1)) local temp while true; do ((i++)) while ((arr[i] < pivot && i <= high)); do ((i++)) done ((j--)) while ((arr[j] > pivot && j >= low)); do ((j--)) done if ((i >= j)); then echo "$j" return fi temp=${arr[i]} arr[i]=${arr[j]} arr[j]=$temp done } quick_sort() { local low=$1 local high=$2 if ((low >= high)); then return fi local pivot pivot=$(partition "$low" "$high") quick_sort "$low" "$pivot" quick_sort $((pivot + 1)) "$high" } quick_sort 0 $((${#arr[@]} - 1)) echo "Sorted array: ${arr[*]}"
运行结果
执行修正后的代码,输出为:
Sorted array: 1 2 3 4 5 7 8 9
内容的提问来源于stack exchange,提问作者Hi Byee
相关产品推荐
相关产品推荐

