Assignment9 July 2024
Assignment9 July 2024
Selection sort creates a sub-list, LHS of the ‘min’ element is already sorted and RHS is yet to
be sorted. Starting with the first element the ‘min’ element moves towards the final element
2. What is the correct order of insertion sort (in ascending order) of the array arr[5]={8 3 5 9 4}?
a) {3 8 5 9 4} {3 5 8 9 4}{3 4 5 8 9}
b) {3 8 5 9 4} {3 5 8 9 4} {3 5 8 4 9} {3 5 4 8 9}{3 4 5 8 9}
c) {3 8 5 9 4}{3 4 8 5 9}{3 4 5 8 9}{3 4 5 8 9}
d) {8 3 5 4 9}{8 3 4 5 9}{3 4 5 8 9}
Solution: (a) In insertion sort, we start from the second number onwards and place it in appropriate
position before its current position. Thus, the correct answer is (a).
4. Select the code snippet which performs unordered linear search iteratively?
Solution: (a)
Unordered term refers to the given array, that is, the elements need not be ordered. To search
for an element in such an array, we need to loop through the elements until the desired
element is found.
5. What is the best case and worst case complexity of ordered linear search?
a) O(nlogn), O(logn)
b) O(logn), O(nlogn)
c) O(n), O(1)
d) O(1), O(n)
Solution: (d)
Although ordered linear search is better than unordered when the element is not present in the
array, the best and worst cases still remain the same, with the key element being found at first
position or at last position respectively.
7. Given an array arr = {45, 77, 89, 91, 94, 98,100} and key = 100; what are the mid
values (corresponding array elements) generated in the first and second iterations?
a) 91 and 98
b) 91 and 100
c) 91 and 94
d) 94 and 98
b) int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length; k++)
{
if(arr[k] < arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
c) int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length-1; k++)
{
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
d) int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length; k++)
{
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
Solution: (a)
Starting with the first element as ‘min’ element, selection sort loops through the list to
select the least element which is then swapped with the ‘min’ element.
9. Consider the array A[]= {5,4,9,1,3} apply the insertion sort to sort the array . Consider
the cost associated with each sort (swap operation) is 25 rupees, what is the total cost
of the insertion sort when element 1 reaches the first position of the array?
a) 25
b) 50
c) 75
d) 100
Solution: (b)
When the element 1 reaches the first position of the array two comparisons are only
required hence 25 * 2= 50 rupees.
*step 1: 4 5 9 1 3.
*step 2: 1 4 5 9 3
a) 5,4
b) 5,5
c) 4,4
d) 3,4
Solution: (c)