Читаем 100 Shell Programs in Unix полностью

? ? ?91 ? ? ?92 ? ? ?93 ? ? ?94 ? ? ?95 ? ? ?96 ? ? ?97 ? ? ?98 ? ? ?99

? ? ?0 * * *1 * * *2 * * *3 * * *4 * * *5 * * *6 * * *7 * * *8 * * *9

* * *10 * * *11 * * *12 * * *13 * * *14 * * *15 * * *16 * * *17 * * *18

* * *19 * * *20 * * *21 * * *22 * * *23 * * *24 * * *25 * * *26 * * *27

* * *28 * * *29 * * *30 * * *31 * * *32 * * *33 * * *34 * * *35 * * *36

* * *37 * * *38 * * *39 * * *40 * * *41 * * *42 * * *43 * * *44 * * *45

* * *46 * * *47 * * *48 * * *49 * * *50 * * *51 * * *52 * * *53 * * *54

* * *55 * * *56 * * *57 * * *58 * * *59 * * *60 * * *61 * * *62 * * *63

* * *64 * * *65 * * *66 * * *67 * * *68 * * *69 * * *70 * * *71 * * *72

* * *73 * * *74 * * *75 * * *76 * * *77 * * *78 * * *79 * * *80 * * *81

* * *82 * * *83 * * *84 * * *85 * * *86 * * *87 * * *88 * * *89 * * *90

* * *91 * * *92 * * *93 * * *94 * * *95 * * *96 * * *97 * * *98 * * *99

* * *

Binary Search

Suppose that the elements of the array A are sorted in ascending order, if the elements are numbers, or dictionary order if the elements are alphanumeric in nature. The best searching algorithm, called binary search, is used to find the location of the given element.

96. Write a shell script to implement the binary search algorithm.

$vi prg96

clear

echo Enter size of array

read size

echo Enter elements

i=0

while [ $i -lt $size ]

do

read a[$i]

i=‘expr $i + 1’ done i=0

while [ $i -lt $size ]

do

echo “${a[$i]}”

i=‘expr $i + 1’

done

echo Enter search element read num beg=0

last=‘expr $size - 1’ found=0

while [ $found -eq 0 -a $beg -le $last ]

do

mid=‘expr \( $beg + $last \) / 2

if test ${a[$mid]} -eq $num

then

echo Element is found echo Position is $mid found=1

elif ${a[$mid]} -gt $num

then

last=‘expr $mid - 1’

else

beg=‘expr $mid + 1’

fi

done

if test $found -eq 0

then

echo element is not found

fi

Sample Run

$sh prg96

Enter size of array

7

Enter elements

3

4

5

6

7

8

9

Enter search element

5

Element is found

Position is 2

Sample Run

$sh prg96

Enter size of array

6

Enter elements

4

5

6

7

8

9

Enter search element

1

element is not found

97. Temperature of a city in Fahrenheit degree is input through the keyboard WAP to convert this temperature into Centigrade degrees.

              Formula is

              c/100=f-32/180

              f=9/5*c+32

$vi prg97

clear

echo Enter temperature in Celsius scale :

read c

f=‘echo 9 / 5 \* $c + 32 | bc’

echo

echo Equivalent temperature in Fahrenheit =  $f

Sample Run

$sh prg97

Enter temperature in Celsius scale :

60

Equivalent temperature in Fahrenheit = 92

98. In a town, the percentage of men is 52. Rest all are women. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, WAP to find the total number of illiterate men and women. The population of the town is 80,000.

$vi prg98

clear

a=80000

totman =‘expr \( $a \* 52 \) / 100’

totwman=‘expr $a - $totman’

totLitPeople = ‘expr \( $a \* 48 \) / 100’

litman=‘expr \( $a \* 35 \) / 100’

litwman=‘expr $totLitPeople - $litman’

ilitman=‘expr $totman - $litman’

ilitwman=‘expr $totwman - $litwman’

echo ‘total man = ‘$totman

echo ‘total woman = ‘$totwman

echo ‘literate man = ‘$litman

echo ‘literate woman = ‘$litwman

echo ‘illiterate man = ‘$ilitman

echo ‘illiterate woman = ‘$ilitwman

Sample Run

$sh prg98

total man          = 41600

total woman        = 38400

literate man       = 28000

literate woman     = 13600

illiterate man     = 13600

illiterate woman   = 24800

99. If the three sides of a triangle are entered through the keyboard. WAP to check whether the triangle is equilateral, isosceles, or scalene triangle.

$vi prg99

clear

echo Enter three sides of the triangle

read a b c

echo

if [ $a -eq $b -a $a -eq $c ]

then

echo Triangle is Equilateral

elif [ $a -eq $b -o $a -eq $c -o $b -eq $c ]

then

echo Triangle is Isosceles

elif    echo Triangle is Scalene

fi

Sample Run

$sh prg99

Enter three sides of the triangle

30 75 75

Triangle is Isosceles

Enter three sides of the triangle

60 60 60

Triangle is Equilateral

Enter three sides of the triangle

38 30 35

Triangle is Scalene

100. An Insurance company follows following rules to calculate premium.

(

i

Перейти на страницу:

Похожие книги

Компьютерные сети. 6-е изд.
Компьютерные сети. 6-е изд.

Перед вами шестое издание самой авторитетной книги по современным сетевым технологиям, написанное признанным экспертом Эндрю Таненбаумом в соавторстве со специалистом компании Google Дэвидом Уэзероллом и профессором Чикагского университета Ником Фимстером. Первая версия этого классического труда появилась на свет в далеком 1980 году, и с тех пор каждое издание книги неизменно становилось бестселлером. В книге последовательно изложены основные концепции, определяющие современное состояние компьютерных сетей и тенденции их развития. Авторы подробно объясняют устройство и принципы работы аппаратного и программного обеспечения, рассматривают все аспекты и уровни организации сетей — от физического до прикладного. Изложение теоретических принципов дополняется яркими, показательными примерами функционирования интернета и компьютерных сетей различного типа. Большое внимание уделяется сетевой безопасности. Шестое издание полностью переработано с учетом изменений, произошедших в сфере сетевых технологий за последние годы, и, в частности, освещает такие технологии, как DOCSIS, 4G и 5G, беспроводные сети стандарта 802.11ax, 100-гигабитные сети Ethernet, интернет вещей, современные транспортные протоколы CUBIC TCP, QUIC и BBR, программно-конфигурируемые сети и многое другое.

Дэвид Уэзеролл , Ник Фимстер , Эндрю Таненбаум

Учебные пособия, самоучители