In: Computer Science
Program in Bash: Write a program using bash script that can read a file from the same directory, sort the nonrepeating integers from 0-9 from smallest to largest, and output the results on the same line. Do not use the sort function.
ANSWER:
I have provided the properly commented
and indented code so you can easily copy the code as well as check
for correct indentation.
I have provided the output image of the code so you can easily
cross-check for the correct output of the code.
Have a nice and healthy day!!
CODE
# defining file name
file='file.txt'
# defining empty array
arr=()
# counter for array
i=1
# looping to each line of file
while read line; do
#Reading each line
# storing value to array
arr[i]=$line
# incrementing loop counter
i=$((i+1))
done < $file
# displaying array
echo "Array is: ${arr[@]}"
# Performing Bubble sort
# fetching length of array
n=${#arr[@]}
# looping for bubble sort
# looping for each element in array
for ((i = 0; i<$n; i++))
do
# placing greatest value to n-i-1
for((j = 0; j<$((n-i-1)); j++))
do
# checking for condition to swap
if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
then
# swaping element
temp=${arr[j]}
arr[$j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
done
# displaying sorted array
echo "Sorted Array: ${arr[@]}"
INPUT IMAGE(file.txt)
OUTPUT IMAGE