Professional Documents
Culture Documents
NS Assignment 1
NS Assignment 1
20/08/2022
Assignment 1: Write a menu driven program to accept two integers and perform the four
basic arithmetic calculations addition, subtraction, multiplication and division using functions.
Algorithm:
a) Addition( a, b )
Adds the numbers a and b
Begin
set a variable sum to (a + b)
return sum
End
b) Subtraction( a, b )
Subtracts the numbers a and b
Begin
set a variable sub to (a - b)
return sub
End
c) Mult( a, b )
Multiplies the numbers a and b
Begin
set a variable mul to (a * b)
return mul
End
d) Div( a, b )
Divides the numbers a and b
Begin
set a variable div to (a / b)
return div
End
Implementation in Shell
#!/bin/bash
# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------
4
addition() {
sum=`expr $1 + $2`
echo $sum
}
subtraction() {
diff=`expr $1 - $2`
echo $diff
}
multiplication() {
prod=`expr $1 \* $2`
echo $prod
}
division() {
quot=`echo "scale=2;($1/$2)"|bc`
echo $quot
}
read -p "Enter 1st number " a
read -p "Enter 2nd number " b
echo "Enter 1 to perform Addition"
echo "Enter 2 to perform Subtraction"
echo "Enter 3 to perform Multiplication"
echo "Enter 4 to perform Division"
read -p "Enter your choice " op
case $op in
1)
x=$(addition $a $b)
echo "The sum is: $x"
;;
2)
x=$(subtraction $a $b)
echo "The difference is: $x"
;;
3)
x=$(multiplication $a $b)
echo "The product is: $x"
;;
4)
x=$(division $a $b)
echo "The division is: $x"
5
;;
*)
echo "Invalid input"
esac
Output Sets
➜ assignments ./ass1.sh
Enter 1st number 13
Enter 2nd number 56
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 1
The sum is: 69
➜ assignments ./ass1.sh
Enter 1st number 56
Enter 2nd number 34
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 2
The difference is: 22
➜ assignments ./ass1.sh
Enter 1st number 44
Enter 2nd number 66
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 3
The product is: 2904
➜ assignments ./ass1.sh
Enter 1st number 48
Enter 2nd number 31
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 4
The division is: 1.54
6
25/08/2022
Assignment 2: Find the sum of the following series:
a. 1+2+3+.......+n
b. 1+(1+2)+(1+2+3)+.......(1+2+3+.....+n)
Algorithm:
a) Begin
read num from the user
set sum = n * (n + 1) / 2
print sum
End
b) Begin
read num from the user
set i to 0
while i <= num do
set j=1
while j <= i do
set sum = sum + j
set j = j + 1
end of while
I=i+1
end of while
End
Implementation in Shell
a)
#!/bin/bash
# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------
else
echo "Not enough arguments"
fi
Output Sets
➜ assignments ./ass2a.sh
Not enough arguments
➜ assignments ./ass2a.sh 20
The sum of natural numbers up until 20 is 210
➜ assignments ./ass2a.sh -1
Invalid argument
b)
#!/bin/bash
# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------
if [ $# -ge 1 ]; then
n=$1
if [ $n -le 0 ]; then
echo "Invalid argument"
exit 1
fi
# Main code
i=1
sum=0
while [ $i -le $n ]; do
j=1
while [ $j -le $i ]; do
8
else
echo "Not enough arguments"
fi
Output Sets
➜ assignments ./ass2b.sh
Not enough arguments
➜ assignments ./ass2b.sh 2
The Sum of the Series= 4
➜ assignments ./ass2b.sh 20
The Sum of the Series= 1540
➜ assignments ./ass2b.sh -1
Invalid argument
9
03/09/2022
Assignment 3: Generate all the Armstrong numbers within a user given range through
command line arguments.
Algorithm
Step 1: Begin
Step 2: armstrong():
1. Set num:=argument 1, temp:=num, sum:=0, count:=0
2. while temp>0 do
Set count:=count+1
Set temp:=temp/10
3. done
4. Set temp:=num
5. while num>0 do
Set d:=num%10
Set sum:=sum+(d to the power of count)
Set num:=num/10
6. done
7. if sum=temp then
Return 0
8. Else,
Return 1
9. End of if
Step 3: Set lowerlimit:=argument 1, upperlimit:=argument 2
Step 4: for i:= lowerlimit to upperlimit step +1 do
1. Calling armstrong() with i as parameter
2. Set res:=value returned by armstrong()
3. if res=0 then
Print(i)
4. End of if
Step 5: done
Step 6: End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
arms() {
aNum=$1
10
# Calculating if Armstrong
aNumC=$aNum # Reinitializing the copy value
aSum=0
while [ $aNumC -gt 0 ]; do
aRemain=$(( $aNumC%10 ))
aExp=$(( $aRemain**$aNumDig ))
aSum=$(( $aSum+$aExp ))
aNumC=$(( $aNumC/10 ))
done
lowerLim=$1
upperLim=$2
Output Sets
➜ assignments ./ass3.sh
Incorrect number of arguments
➜ assignments ./ass3.sh 100 200
153
➜ assignments ./ass3.sh 100 1000
153
370
371
407
➜ assignments ./ass3.sh 1000 5000
1634
➜ assignments ./ass3.sh 1000
Incorrect number of arguments
12
06/09/2022
Assignment 4: Print the following patterns:
a.
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
b.
*
* *
* * *
* * * *
* * * * *
c.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Algorithm
a) Pattern1( n )
Here n is the dimension of the pattern
Begin
for i:=1 to n do
for i:=1 to n do
if j >= i then
print j
else
print space
end if
print space
end of for
go to new line
end of for
End
b) Pattern2 ( n )
Begin
for i:=1 to n step +1 do
Set k:=0
for space:=1 to (n-i) step +1 do
Print “ ”
done
while k not equal to i do
13
Print “*”
Set k:=k+1
done
done
End
c) Pattern3 ( n )
Begin
Set coef:=1
for i:=1 to n-1 step +1 do
for space:=1 to (n-i) step +1 do
Print “ ”
done
for j:=0 to i step +1 do
if j=0 or i=0 then
Set coef:=1
else,
Set coef:=coef*(i-j+1)/j
End of if
Print(coef)
done
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science,
# Scottish Church College, Kolkata
# ------------
if [ $# -ne 2 ]; then
echo "Not enough args. Format: ./pattern.sh dimension case"
exit
fi
n=$1
choice=$2
pattern1 () {
for (( i=1; i<=n; i++ )) {
for (( j=1; j<=$n; j++ )) {
if [ $j -ge $i ]; then
echo -n $j
else
echo -n " "
14
fi
echo -n " "
}
echo
}
}
pattern2 () {
for (( i=1; i<=$n; i++ )) {
k=0
for (( space=1; space<=$(($n-$i)); space++ )) {
echo -n " "
}
while [ $k -ne $i ]; do
echo -n "* "
k=$(($k+1))
done
echo
}
}
pattern3 () {
coef=1
for(( i=0 ; i<$n ; i++ )); do
for(( space=1 ; space <= $n-$i ; space++ )); do
echo -n " "
done
for(( j=0 ; j<=$i ; j++ )); do
if [ $j -eq 0 -o $i -eq 0 ]; then
coef=1;
else
coef=$(($coef*($i-$j+1)/$j))
fi
echo -n "$coef "
done
echo
done
}
case $choice in
0)
pattern1
;;
1)
pattern2
;;
15
2)
pattern3
;;
*)
esac
Output Sets
➜ assignments ./ass4.sh 4 0
1 2 3 4
2 3 4
3 4
4
➜ assignments ./ass4.sh 5 1
*
* *
* * *
* * * *
* * * * *
➜ assignments ./ass4.sh 5 2
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
➜ assignments ./ass4.sh
Not enough args. Format: ./pattern.sh dimension case
16
06/09/2022
Assignment 5: Calculate the factorial of a number using functions.
Algorithm
Begin
set n:=argument 1, fact:=1
while n>1 do
set fact:=fact*n
set n:=n-1
done
print fact
Stop
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
fact() {
num=$1
if [ $num -eq 0 ]; then
echo 1
return
fi
fact=1
while [ $num -gt 1 ]; do
fact=$(($fact * $num)) #fact = fact * num
num=$(($num - 1)) #num = num - 1
done
echo $fact
}
Output Sets
➜ assignments ./ass5.sh
Not enough arguments
➜ assignments ./ass5.sh 5
Factorial of 5 is 120
➜ assignments ./ass5.sh 10
Factorial of 10 is 3628800
➜ assignments ./ass5.sh 3
Factorial of 3 is 6
18
07/09/2022
Assignment 6: Simulate the wc command with its options -l, -w and -c
Algorithm
Begin
Execute only if argument 2 is an executable file
Under case block with choice as argument 1,
1.
set nol:=0
while lines present in the file do
set nol:=nol+1
done
print(nol)
Terminating from case block
2.
set now:=0
while lines present in the file do
Accessing all the words in a line
Set now:=now+count of words in a line
done
Print(now)
Terminating from case block
3.
Set noc:=0
while lines present in the file do
Accessing all the words in a line
for words present in the line do
Extracting all the characters from a word and storing in char
Set noc:=noc+char
done
done
Print(noc)
Terminating from case block
4.
Print “Invalid Option”
End of case block
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
19
# ------------
'-w')
now=0
while read line; do
set $line
now=`expr $now + $#`
done
echo "Number of words is $now"
;;
'-c')
while read line; do
set $line
for word in $*; do
char=`expr length $word`
noc=`expr $noc + $char`
done
done
echo "Number of characters is $noc"
;;
*)
echo "Invalid Option"
;;
esac
else
echo "Not enough arguments"
fi
20
Output Sets
13/09/2022
Assignment 7: Input an array of integers and find out the maximum and minimum value.
Algorithm
Begin
Dynamically accepting input in the array a
Set min:=1 st element of a, max:=1 st element of a
for i:=through all the elements of a do
if i<min then
Set min:=i
End of if
if i>max then
max:=i
End of if
done
Print(min) and Print(max)
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
min=${a[0]}
max=${a[0]}
for i in ${a[@]}; do
if [ $i -lt $min ]; then
min=$i
fi
if [ $i -gt $max ]; then
max=$i
fi
done
22
Output Sets
➜ assignments ./ass7.sh
Enter your values, type Ctrl+D when done
4
34
9
35
2
0
-1
Min: -1
Max: 35
➜ assignments ./ass7.sh
Enter your values, type Ctrl+D when done
-10000
3
-20
-90
Min: -10000
Max: 3
23
14/09/2022
Assignment 8: Sort an array of elements in descending order using Bubble Sort
mechanism.
Algorithm
Begin
Dynamically accepting input in the array a
Set n:=number of elements in a
for i:=1 to n-1 step +1 do
for j:=1 to n-i-1 step +1 do
if j-th element<(j+1)th element of a then
Set temp:=jth element of a
Set jth element:=(j+1)th element of a
Set (j+1)th element:=temp
End of if
done
done
Print(a)
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
Output Sets
➜ assignments ./ass8.sh
Enter your values: 45 78 3 90 45
Sorted array: 90 78 45 45 3
➜ assignments ./ass8.sh
Enter your values: 1 2 3 4 5 67 7 8
Sorted array: 67 8 7 5 4 3 2 1
25
27/09/2022
Assignment 9: Check whether a given integer or a string is a palindrome or not using
separate functions.
Algorithm
Begin
palin():
Set str:=argument 1
Set str1:=reverse of str
if str=str1 then
Print “str is a palindrome”
Else,
Print “str is not a palindrome”
End of if
Read(s)
Calling palin() with s as parameter
Stop
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
else
26
Output Sets
27/09/2022
Assignment 10: Display all the integer palindromes within a user given range through
command line arguments.
Algorithm
Begin
palin():
Set str:=argument 1
Set str1:=reverse of str
if str=str1 then
Print “str is a palindrome”
Else,
Print “str is not a palindrome”
End of if
Read upperlimit and lowerlimit
for i:=lowerlimit to upperlimit do
palin(i)
end of for
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
palin() {
str=$1
str1=`echo $str | rev`
if [ "$str" == "$str1" ]; then
echo $str
fi
}
lowerlimit=$1
upperlimit=$2
for (( i=lowerlimit; i<=upperlimit; i++ )); do
palin $i
done
28
Output Sets
28/09/2022
Assignment 11: Accept a password and check whether it is strong or a weak one.
Algorithm
Begin
Define arrays for special characters, numericals, small characters and
capital characters.
Set the arrays to all the related characters
Read password
Set sp, cl, sm, nu to 0
For letter in password do
If letter in specialChars do
sp = 0
End of if
If letter in numericals do
nu = 0
End of if
If letter in smallChar do
sm = 0
End of if
If letter in bigChars do
cl = 0
End of if
Done
Set sum to sp+nu+sm+cl
If sum >= 4 then
Print “Password is strong”
Else
Print “Password is weak”
End of if
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
smallLetters=("q w e r t y u i o p a s d f g h j k l z x c v b n
m")
capitalLetters=("Q W E R T Y U I O P A S D F G H J K L Z X C V B N
M")
Output Sets
➜ assignments ./ass11.sh
Enter your password: scottish1234
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish1234
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish&$#@
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish*&&318943*&
31
Algorithm
Begin
Read(m)
Under case block with choice as m,
90-100:
Print “Outstanding”
Terminating from case block
60-89:
Print “Excellent”
Terminating from case block
40-69:
Print “Good”
Terminating from case block
0-39:
Print “Try Again”
Terminating from case block
Otherwise,
Print “Invalid input”
End of case block
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
case $marks in
[1][0][0])
echo "Outstanding"
;;
[9][0-9])
echo "Outstanding"
;;
[6-8][0-9])
echo "Excellent"
;;
[4-5][0-9])
echo "Good"
;;
[0-3][0-9])
echo "Try again"
;;
*)
echo "Invalid input"
exit 1
esac
Output Sets
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 10
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 56
Good
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 99
Outstanding
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 30
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 34
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 65
Excellent
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 40
Good
➜ assignments ./ass12.sh
Enter the percentage marks of the student: -87
Invalid input
33
29/10/2022
Assignment 13: Find out the n-th term of the Fibonacci series.
Algorithm
Begin
fibonacci():
Set nf:=argument 1, b:=1, s:=0
for i=:=1 to nf step +1 do
Set s:=s+b
Set b:=s-b
done
Print(s)
Read(n)
if n>0 then,
Calling fibonacci() with n as parameter
else,
Print “Invalid input”
end of if
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
fibonacci() {
nf=$1
s=0
b=1
for(( i=1 ; i<=$nf ; i++ )); do
s=$(($s+$b))
b=$(($s-$b))
done
echo "The n-th term of Fibonacci Series is $s"
}
if [ $n -le 0 ]; then
echo "Invalid argument"
exit 1
fi
fibonacci $n
else
echo "Not enough arguments"
fi
Output Sets
➜ assignments ./ass13.sh
Not enough arguments
➜ assignments ./ass13.sh 7
The n-th term of Fibonacci Series is 13
➜ assignments ./ass13.sh 40
The n-th term of Fibonacci Series is 102334155
➜ assignments ./ass13.sh 1
The n-th term of Fibonacci Series is 1
35
1/11/2022
Assignment 14: Check whether a given number through command line argument is prime
or composite.
Algorithm
Begin
isPrime():
Set num:=argument 1
if num=0 then,
Return 1
else if num=1 then,
Return 1
end of if
Set halfNum:=num/2
for i:=2 to halfNum step +1 do
Set m:=num%i
if m=0 then,
Return 1
end of if
done
Return 0
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
isPrime() {
36
num=$1
if [ $num -eq 0 ]; then
return 1
elif [ $num -eq 1 ]; then
return 1
fi
halfNum=$(( $num/2 ))
for (( i=2; i<=$halfNum; i++ )); do
modulo=$(( $num%$i ))
if [ $modulo -eq 0 ]; then
return 1
fi
done
return 0
}
else
echo "Not enough arguments"
fi
Output Sets
➜ assignments ./ass14.sh 14
The given number, 14, is composite
➜ assignments ./ass14.sh 41
The given number, 41, is a prime
➜ assignments ./ass14.sh 2
The given number, 2, is a prime
➜ assignments ./ass14.sh 2657
The given number, 2657, is a prime
37
3/11/2022
Assignment 15: Use functions to find the HCF and LCM of two numbers.
Algorithm
Begin
hcf():
Set a:=argument 1, b:= argument 2
while b not equal to 0 do
Set r:=a%b
Set a:=b, b:=r
done
Return a
lcm():
Set x:=argument 1, y:= argument 2
if x>;y then,
Set max:=x
else,
Set max:=y
end of if
while 1 do
Set p:=max%x, q:=max%y
if p=0 and q=0 then,
Print(max)
Terminate from method
end of if
Set max:=max+1
Done
Read(c)
Under case block with c as choice
1.
Read(n1) and Read(n2)
Calling hcf() with n1 and n2 as parameters
Print the value returned by hcf()
Terminating from case block
2.
Read(n1) and Read(n2)
Calling lcm() with n1 and n2 as parameters
Terminating from case block
3.
Print “Wrong choice”
End of case block
End
Implementation in Shell
38
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
hcf() {
a=$1
b=$2
while [ $b -ne 0 ]
do
r=`expr $a % $b`
a=$b
b=$r
done
return $a #a stores the hcf
}
lcm() {
x=$1
y=$2
if [ $x -gt $y ] #for finding the greater no of the two
then
max=$x
else
max=$y
fi
while [ 1 ]
do
p=`expr $max % $x`
q=`expr $max % $y`
if [ $p -eq 0 -a $q -eq 0 ]
then
echo "LCM is=$max"
break #exits from while loop
fi
max=`expr $max + 1`
done
}
echo "1. HCF"
echo "2. LCM"
echo "Enter your choice"
read c #stores choice
39
case $c in
1)
echo "Enter the first number"
read n1
echo "Enter the second number"
read n2
hcf $n1 $n2
echo "HCF is = $?"
;;
2)
echo "Enter the fist number"
read n1
echo "Enter the second number"
read n2
lcm $n1 $n2
;;
*)
echo "It was a wrong choice"
;;
esac
Output Sets
➜ assignments ./ass15.sh
1. HCF
2. LCM
Enter your choice
1
Enter the first number
34
Enter the second number
56
HCF is = 2
➜ assignments ./ass15.sh
1. HCF
2. LCM
Enter your choice
2
Enter the fist number
56
Enter the second number
2
LCM is=56
40
5/11/2022
Assignment 16: Input two integer matrices and perform matrix addition.
Algorithm
Begin
printMat():
Set matrix := argument 1
Set r:= argument 2, c := argument 3
for j := 0 to r step +1 do
for i := 0 to c step +1 do
Set index := j * c + i
Print matrix[index]
done
done
Print matrix1
Print matrix2
Set k := 0
Initialise empty array matrix3
for j := 0 to rows step +1 do
for i := 0 to cols step +1 do
Set index := j * c + i
matrix3[k]=$((${matrix1[index]} + ${matrix2[index]}))
k=$((k+1))
done
done
Print matrix3
End
Implementation in Shell
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
41
echo
echo "Input the first matrix"
echo
echo "Input the second matrix"
k=0
matrix3=()
42
Output Sets
➜ assignments ./ass16.sh
Enter the number of rows: 3
Enter the number of cols: 3
1/12/2022
Assignment 17: Input two integer matrices and perform matrix multiplication.
Algorithm
Begin
printMat():
Set matrix := argument 1
Set r:= argument 2, c := argument 3
for j := 0 to r step +1 do
for i := 0 to c step +1 do
Set index := j * c + i
Print matrix[index]
done
done
Read the first matrix in one dimensional row major form and set to matrix1
Read the second matrix in one dimensional row major form and set to matrix2
Print matrix1
Print matrix2
Print matrix3
End
Implementation in Shell
45
#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
echo
echo
echo "Input the second matrix"
done
echo
done
k=0
matrix3=()
for((i=0; i<R1; i++))
do
for((j=0; j<C2; j++))
do
index=$((i*C2+j))
sum=0
for((k=0; k<R2; k++)); do
idx1=$((i*C1+k))
idx2=$((k*C2+j))
mul=$((${matrix1[idx1]} * ${matrix2[idx2]}))
sum=$(($sum + $mul))
done
matrix3[index]=$sum
done
done
echo "Multiplication of two matrix"
for((i=0; i<R1; i++))
do
for((j=0; j<C2; j++))
do
index=$((i*cols+j))
echo -n "${matrix3[index]} "
done
echo
done
Output Sets
➜ assignments ./ass17.sh
Enter the number of rows of the first matrix: 3
Enter the number of cols of the first matrix: 2
47
3/12/2022
Assignment 18: Accept an array of integers and perform linear and binary search using
separate functions.
Algorithm
Begin
Step 1: Input the length of array
Step 2: Input the elements of the array
Step 3: Input the number to searched
Step 4: linear_search()
1. Variable i is initialised to 0 for traversing the array
2. Begin while(i < length of array) loop
- Check if current element is equal to the element being searched, if
true, ret=i and return
- Increment i by 1
3. ret=-1 (element not found)
Step 5: selection_sort()
1. Initialise i with 0 for outer loop
2. Begin outer loop while(i < length of array)
- Initialise j with i+1 for inner loop
- Begin inner loop while(j < length of array)
- if element at j is less than element at i, swap elements
- Increment j by 1
- Increment i by 1
Step 6: binary_search()
1. Initialise lower with 0 and upper with length of array - 1
2. Begin loop while( lower <= upper)
- Declare mid with (lower+upper)/2
- If element at mid equals element being searched, ret=mid and return
- If element at mid is less than element being searched, lower =
mid+1, else upper = mid-1
3. ret=-1 (element not found)
Step 7: check()
1. If ret == -1, element was not found, printing appropriate message
2. Else element was found at index: ret, printing appropriate message
Step 8: Using linear search, calling linear_search() and then check()
Step 9: Using binary search, calling selection_sort() to sort array and then calling
binary_search() and check()
End
Implementation in Shell
#!/bin/bash
49
selection_sort () {
i=0
while [ $i -lt $n ]
do
j=`expr $i + 1`
while [ $j -lt $n ]
do
if [ ${a[$j]} -lt ${a[$i]} ]
then
temp=${a[$j]}
a[$j]=${a[$i]}
a[$i]=$temp
fi
j=`expr $j + 1`
done
i=`expr $i + 1`
done
}
binary_search () {
lower=0
upper=`expr $n - 1`
while [ $lower -le $upper ]
do
mid=`expr $upper + $lower`
mid=`expr $mid / 2`
if [ ${a[$mid]} -eq $victim ]
50
then
ret=$mid
return
fi
if [ ${a[$mid]} -lt $victim ]
then
lower=`expr $mid + 1`
else
upper=`expr $mid - 1`
fi
done
ret=-1
}
check () {
if [ $ret -eq -1 ]
then
echo "Item not found"
else
echo "Item found"
fi
}
Output Sets
➜ assignments ./ass18.sh
Enter the Total numbers :
5
Enter numbers:
6 7 4 5 2
Enter number to be searched:
1
Using linear search
Item not found
Using binary search
Item not found
➜ assignments ./ass18.sh
Enter the Total numbers :
10
Enter numbers:
51
8 4 0 2 8 5 3 6 11 65
Enter number to be searched:
5
Using linear search
Item found
Using binary search
Item found