10 August 2012

Insertion Sort Using Shell Script

1 comment

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...

1 comment:

  1. Insertion Sort in C

    Insertion Sort is a simplest array data or data Sorting algorithm which sorts the array elements by shifting elements one by one and inserting each element into its proper position.

    ReplyDelete