10 August 2012

Insertion Sort Using Shell Script

2 comments

Q. How do I write Insertion Sort in Bash


Ans:

#!/bin/bash
echo "enter the number"
read n
echo "enter number in an array"
for((i=0;i<n;i++))
do
read arr[$i]
done
#logic for insertion sort
for((i=1;i<n;i++))
do
j=$i-1
temp=${arr[$i]}
while((j>=0 && arr[j]>temp))
do
arr[$j+1]=${arr[$j]}
j=$j-1
done
arr[j+1]=$temp
done
#printing sorted array
echo "printing sorted array"
for((i=0;i<n;i++))
do
echo ${arr[$i]}
done


Output


insertion sort output

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

2 comments:

  1. Thanks again, this was exactly what I needed! This article of Wheel Spinner is full of helpful info. Use Wheel Spinner to add spontaneity to everyday decisions. Whether for fun or productivity, it gets the job done quickly.

    ReplyDelete