Describe an algorithm that takes a list of n integers a1 a2
Solution
1). Describe an algorithm that takes a list of n integers a1, a2, ….., an and find the average of the largest and smallest integers in the list
Ans) .
procedure averageOfLargestAndSmallest(a1,a2,…,an: Integers)
largest: = a1
smallest: = a1
for i : = 2 to n
begin
if ai > largest then
largest: = ai
if ai < smallest then
smallest: = ai
end
average: =( largest + smallest)/2.
****************************************************************************************************************
2). Ans: Use the bubble sort algorithm:
20 64 77 50 42 22
Original Array: 20 64 77 50 42 22
Pass 1:
20 64 77 50 42 22 à no change if 20<64
20 64 77 50 42 22 à no change if 64<77
20 64 50 77 42 22 à if 77<50 condition fails then swap 77 and 50
20 64 50 42 77 22 à if 77<42 condition fails then swap 42 and 77
20 64 50 42 22 | 77 à if 77<22 condition fails then swap 77 and 22
Pass 2:
20 64 50 42 22 |77 à no change if 20<64
20 50 64 42 22 |77 à if 64<50 condition fails then swap 64 and 50
20 50 42 64 22 |77 è if 64<42 condition fails then swap 64 and 42
20 50 42 22 |64 77 à if 64<22 condition fails then swap 64 and 22
Pass 3:
20 50 42 22 |64 77 à no change if 20<50
20 42 50 22 |64 77 à if 50<42 condition fails then swap 42 and 50
20 42 22 |50 64 77 à if 50<22 condition fails then swap 22 and 50
Pass 4:
20 42 22 |50 64 77 à no change if 20<42
20 22 |42 50 64 77 à if 42<22 condition fails then swap 22 and 42
Pass 5:
20 22 42 50 64 77 à no change if 20<22
sorted elements After Bubble Sort:
20 22 42 50 64 77
****************************************************************************************************************
3Ans) Use the insertion sort algorithm:
Original Array: 20 64 77 50 42 22
20 64 77 50 42 22
20 64 77 50 42 22
20 50 64 77 42 22
20 42 50 64 77 22
20 22 42 50 64 77
sorted elements After insertion Sort:
20 22 42 50 64 77
****************************************************************************************************************
4Ans): Binary search Algorithm
procedure BinarysearchAlg(a1,a2,…,an: Integers)
key:=42
low := 1;
high := n;
do
mid := (low + high) / 2;
if (key< array[mid])
high := mid - 1;
else if (key > a[mid])
low = mid + 1;
} while (key!= a[mid] && low <= high);
if (key == a[mid])
{
print(\"SEARCH SUCCESSFUL \");
}
else
{
print(\"SEARCH FAILED \");
}
Search element:
Step1:
key:=42
List : 10 11 13 15 18 27 29 31 36 42 50 56 70 73 82 96
Low=1
High=16
Step2:
List: 10 11 13 15 18 27 29 31 36 42 50 56 70 73 82 96
Mid=(1+16)/2 =8
If( 36<key) then low=mid+1
Step3:
List: 10 11 13 15 18 27 29 31 36 42 50 56 70 73 82 96
Mid=(9+16)/2 =12
If(70>key) then high=mid-1
Step4:
List: 10 11 13 15 18 27 29 31 36 42 50 56 70 73 82 96
Mid=(9+12)/2 =10
If(50>key) then high=mid-1
Step5:
List: 10 11 13 15 18 27 29 31 36 42 50 56 70 73 82 96
Mid=(9+9)/2 =9
If(42==key) then
42 is found in the list



