I wrote a simple quick sort algorithm. When I run it, it echoes the same array back.
#!/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 >= 0)); 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[*]}"
Output:
Sorted array: 1 8 3 9 4 5 7 2
I am on Windows so i tried it on git-bash and an online bash shell, the outcome was still the same
pivot=$(partition …)runspartitionin a subshell. Any changes toarrinside that subshell are lost when it returns, which is why the array looks unchanged. To fix this issue, callpartitiondirectly so it mutates the global array, and only return the pivot index (writing it intoREPLYor a global variable). Just for exxample: ` partition() { … REPLY=$j; return; } partition "$low" "$high" pivot=$REPLY ` That way the swaps inpartitionpersist and your quick sort works.