Assignment 10 Solution
Assignment 10 Solution
1. In ……………, search start at the beginning of the list and check every element in the
list.
a) Linear search
b) Binary search
c) Hash search
d) Binary tree search
Solution: (a) linear search
3. How can you improve the best-case efficiency in bubble sort? (The input is already
sorted)
a) boolean swapped = false;
for(int j=arr.length-1; j>=0 && swapped; j--)
{
swapped = true;
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
swapped = false;
}
}
}
b) boolean swapped = true;
for(int j=arr.length-1; j>=0 && swapped; j--)
{
swapped = false;
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
ASSIGNMENT 10 SOLUTION
Solution: (c)
A boolean variable ‘swapped’ determines whether any swapping has happened in a particular
iteration, if no swapping has occurred, then the given array is sorted and no more iterations
are required.
4. If for a real continuous function f(x), f(a) × f(b) > 0, then in the range of [a,b] for f(x) =
0, there is (are)
a) Exactly one root
b) no root exists
c) at least one root
d) roots are undermined
Solution: (b). If, f(a) × f(b) < 0 then they have opposite signs; only then root(s) exists.
Since f(x) is continuous between a and b, the function needs to cross the x-axis to have f(x)
solvable. Here, as f(a) × f(b) > 0, so the function does not cross x-axis. Hence, no root
exists.
ASSIGNMENT 10 SOLUTION
5. Assuming an initial range [1,5], the second (at the end of 2 iterations) iterative value of
the root of te−t − 0.3 = 0 using the bisection method is (Note: you need to find the root,
not the function value)
Solution: 2 (short answer type)
t u = 5 and f(t u ) = −0.2663
t l = 1 and f(t l ) = 0.0679
f(t u ) × f(t l ) = 0.0181 < 0
Therefore, at least one root exists between [1,5]
t +t 5+1
Iteration1: t m = u l = =3 Thus, f(t m ) = −0.1506 < 0
2 2
Therefore, at least one root exists between [1,3] and we make t u = 3
tu +tl 3+1
Iteration2: t m = = =2 Hence, the root after the second iteration is 2.
2 2
*(num+2)[0]=*(*((num+2)+0))=*(*(num+2))=*(num[2])=num[2][0]=23
And **(num+1)=*(num[1]+0)=num[1][0]=11
This is example of pointer arithmetic on array.
#include <stdio.h>
int main()
{
int ary[4] = {1, 2, 3, 4};
int *p;
p = ary + 3;
*p = 5;
printf("%d\n", ary[3]);
return 0;
}
a) 2
b) 4
c) 7
d) 5
Solution: (d) The pointer p contains the address of the last element of the array. Assigning the
value at that address to 5 changes the content of the array ary. The last element is replaced
with 5. Thus, ary[3] is 5.
10. What is the solution of the equation given below using Bisection Method upto four
decimal places? (Consider the root lying on positive quadrant only and compute the root
till five iterations only)
f(x) = xe2x − 3x 2 − 5
Solution: 1.0312 (short answer type)
The root lies between 1 and 2. Using bisection method, we can find the root as 1.0312 (upto
three decimal accuracy)