Unit 4 Que & Ans
Unit 4 Que & Ans
1a. Define Sorting? Explain the complexities of selection, insertion and bubble sort?
[L2][CO5] [marks 7]
Ans:
Complexity and running time are often expressed in "Big O notation," which is used to
describe the approximate amount of time an algorithm requires to complete, based the size of
its input.
Selection sort :
Selection sort is an in-place comparison sort. It has O(n2) complexity, making it inefficient on
large lists, and generally performs worse than the similar insertion sort. Selection sort is noted
for its simplicity, and also has performance advantages over more complicated algorithms in
certain situations.
complexities
Selecting the lowest element requires scanning all n elements (this takes n-1 and then
swapping it into the first position. Finding the next lowest element requires scanning all n-1
elements and so on, for (n-1) + (n-2) + ... + 2 + 1 (O(n 2)) comparisons. Each of these scans
requires one swap for n-1 elements.
Insertion Sort :
Insertion sort is a comparison sort in which the sorted array (or list) is built one entry at a
time. Every iteration of insertion sort removes an element from the input data, inserting it into
the correct position in the already-sorted list, until no input elements remain. The choice of
which element to remove from the input is arbitrary, and can be made using almost any
choice algorithm.
Sorting is typically done in-place. The resulting array after k iterations has the property where
the first k+1 entries are sorted. In each iteration the first remaining entry of the input is
removed, inserted into the result at the correct position, thus extending the result.
complexities
Worst case performance: O(n2)
○ Best case performance: O(n)
○ Average case performance: O(n2)
○ Worst case space complexity: O(n) total, O(1) auxiliary
Bubble sort: Bubble sort is a simple sorting algorithm. It works by repeatedly stepping
through the list to be sorted, comparing each pair of adjacent items and swapping them if they
are in the wrong order. The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted. Because it only uses comparisons to operate on elements, it is
a comparison sort.
complexities
1. b. Implement a program that uses a non recursive function to sort the given list of
integers in ascending using bubble sort. [L3][CO4] [8]
#include<stdio.h>
void bubblesort(int[],int);
void main()
inti,n,temp,j,arr[25];
scanf("%d",&n);
scanf("%d",&arr[i]);
bubblesort(arr,n);
void bubblesort(intarr[],int n)
inti,j,temp;
for(i=0 ; i<n ; i++)
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
} }}
printf(" %4d",arr[i]);
}
}
Expected Output:
#include<stdio.h>
void main()
inti,n,temp,j,arr[25];
scanf("%d",&n);
scanf("%d",&arr[i]);
selectionsort(arr,n);
void selectionsort(intarr[],int n)
inti,j,max,temp;
max=i;
{
max=j;
}}
if(max!=i)
temp=arr[i];
arr[i]=arr[max]; arr[max]=temp;
}}
printf(" %d",arr[i]);
}}
Expected output:
Compare minimum with the third element. Again, if the third element is smaller, then
assign minimum to the third element otherwise do nothing. The process goes on until the
last element. Compare minimum with the
remaining elements
3. After each iteration, minimum is placed in the front of the unsorted list.
NOTE: whenever examples of sorting and searching techniques are asked , write each iteration(i.e
each pass) clearly by applying the logic on to the numbers you have taken as example in the
answer
2.b. Implement a program to sort the given list of integers in ascending order using
insertion sort? [L3][CO4] [ 7]
#include <stdio.h>
int main()
{
int n, i, j, key; intarr[64];
3. a. Illustrate an algorithm for selection sort and explain with an example. [L3]
[CO4] [7]
Ans:
In selection sort the list is divided into two sub-lists sorted and unsorted. These two lists are
divided by imaginary wall. We find a smallest element from unsorted sub-list and swap it to
the beginning. And the wall moves one element ahead, as the sorted list is increases and
unsorted list is decreases.
Assume that we have a list of n elements. By applying selection sort, the first element is
compared with all remaining (n-1) elements. The smallest element is placed at the first
location.
Again, the second element is compared with remaining (n-1) elements. At the time of
comparison, the smaller element is swapped with larger element. Similarly, entire array is
checked for smallest element and then swapping is done accordingly. Here we need n-1
passes or iterations tocompletely rearrange the data.
Algorithm:
Selection_Sort( A [ ] , N)
If A[ J ] < A [ POS ]
Set POS = J
End For
End For
Step 6 : Exit
3. b. Explain an algorithm for insertion sort and explain with an illustration.[L3][CO4] [8]
Both the selection and bubble sort algorithms exchange elements. But insertion sort does not
exchange elements. In insertion sort the element is inserted at an appropriate place similar to card
insertion. Here the list is divided into two parts sorted and unsorted sub-lists. In each pass, the first
element of unsorted sub list is picked up and moved into the sorted sub list by inserting it in
suitable position. Suppose we have ‘n’ elements, we need n-1 passes to sort the elements.
Insertion sort works this way: It works the way you might sort a hand of playing cards:
1. We start with an empty left hand [sorted array] and the cards face down on the table
[unsorted array].
2. Then remove one card [key] at a time from the table [unsorted array], and insert it into the
correct position in the left hand [sorted array].
3. To find the correct position for the card, we compare it with each of the cards already in
the hand, from right to left.
INSERTION_SORT (A)
1. FOR j ← 2 TO length[A]
2. DO key ← A[j]
4. i ← j − 1
7. i ← i − 1
8. A[i + 1] ← key
4.a. Implement a C program that uses a non recursive function to search for a Key
value in a given list of integers using linear search method.[L3][CO4] [7]
#include<stdio.h>
void linear
search(int[],int,int);
void main()
{
inti, a[20], n, key;
linear search(a,n,key);
}
void linear search(int a[],intn,int key)
{
inti,flag=0;
for(i = 0; i< n; i++)
{
if(a[i] == key)
{
flag = 1;
break;
}
}
if(flag == 1)
printf("The key elements %d is found at location %d.",key, i + 1);
else
printf("The key element %d is not found in the array.",key);
}
Output:
Enter the size of an array : 5
Enter the array elements: 3 4 5 6 8
Enter the key element: 6
The key element 6 is found at location 4.
4 b. Implement a C program that uses non recursive function to search for a Key value in
a given sorted list of integers by applying binary search method[L3][CO4] [8]
#include<stdio.h> void
binarysearch(int [],int,int);
void main()
{
int a[20], i, n, key;
printf("Enter no of elements: ");
scanf("%d",&n);
printf("Enter the array elements in ascending order: ");
for(i = 0; i< n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element: ");
scanf("%d", &key);
binarysearch(a,n,key);
}
void binarysearch(int a[],intn,int key)
{
inti,low, high, mid;
low = 0;
high = n - 1;
while(high >= low)
{
mid = (low + high) / 2;
if(key == a[mid])
break;
else if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
if(key == a[mid])
printf("The key element %d is found at location %d.", key,mid + 1);
else
printf("The key element %d is not found.",key);
}
Output:
Enter no of elements: 5
Enter the array elements in ascending order: 4 6 8 20 24
Enter the key element: 24
The key element 24 is found at location 5.
Searching is a method to check for an element or retrieve an element from any data structure
where the data is stored. Based on the type of search operation, there are generally two
algorithms defined in C:
Binary Search in C Language we search in the given sorted elements. In this algorithm we
divide sorted elements from the middle and check the lie between which part. Same process
we try until all elements are not read. The time complexity of Binary Search is O(Log n).
1. Linear search is iterative in nature and uses a sequential approach. On the other hand,
Binary search implements divide and conquer approach.
2. The time complexity of linear search is O(N) while binary search has O(log2N).
3. The best case time in linear search is for the first element i.e., O(1). As against, in
binary search, it is for the middle element, i.e., O(1).
4. In linear search, the worst case for searching an element is the N number of
comparison. In contrast, it is a log2N number of comparisons for binary search.
5. Linear search can be implemented in an array as well as in a linked list whereas binary
search can not be implemented directly on a linked list.
6. As we know Binary search requires the sorted array that is the reason It requires
processing to insert at its proper place to maintain a sorted list. On the contrary linear
search does not require sorted elements, so elements are easily inserted at the end of
the list.
7. Linear search is easy to use, and there is no need for any ordered elements. On the
other hand, the Binary search algorithm is however tricky, and elements are necessarily
arranged in order.
8. Since it follows the technique to eliminate half of the array elements, it is more
efficient as compared to linear search for large data.
5 b. Implement an algorithm to search for a Key value in a given list of integers
using binary search method. [L3][CO4] [8]
Algorithm:
1. Begin
2. Set beg = 0
3. Set end = n-1
4. Set mid = (beg + end) / 2
5. while ( (beg <= end) and (a[mid] ≠ item) ) do
6. if (item < a[mid]) then
7. Set end = mid - 1
8. else
9. Set beg = mid + 1
10. endif
11. Set mid = (beg + end) / 2
12. endwhile
13. if (beg > end) then
14. Set loc = -1
15. else
16. Set loc = mid
17. endif
18. End
6. a. Illustrate an algorithm to search for a Key value in a given list of integers using
linear search method.[L3][CO4] [7]
Linear search technique is also known as sequential search technique. Linear search is a
method ofsearching an element in a list in sequence. In this method, the array is searched for
the requiredelement from the beginning of the list/array or from the last element to first
element of array andcontinues until the item is found or the entire list/array has been
searched.
Algorithm:
Go to step 6
Go to step 3
Step 5: If the flag is “element not found”
Advantages:
1. It is a simple and conventional method of searching data. The linear or sequential name
2. The elements in the list can be in any order. i.e. The linear search can be applied on sorted
or
Disadvantage:
1. This method is insufficient when a large number of elements is present in the list.
6.b. Analyse the complexity of linear search and binary search algorithms.[L2][CO4] [8]
Searching is a method to check for an element or retrieve an element from any data structure
where the data is stored. Based on the type of search operation, there are generally two
algorithms defined in C:
Complexity and running time are often expressed in "Big O notation," which is used to
describe the approximate amount of time an algorithm requires to complete, based the size of
its input.
Linear search Complexity:
● Worst case time complexity: O(N)
● Average case time complexity: O(N)
● Best case time complexity: O(1)
● Space complexity: O(1)
In each iteration, the search space is getting divided by 2. That means that in the current
iteration you have to deal with half of the previous iteration array.
Best case could be the case where the first mid-value get matched to the element to be
searched
Asymptotic notations are used to represent the complexities of algorithms for asymptotic
analysis. These notations are mathematical tools to represent the complexities. There are
three notations that are commonly used.
Big Oh Notation
Big-Oh (O) notation gives an upper bound for a function f(n) to within a constant factor.
We write f(n) = O(g(n)), If there are positive constantsn0 and c such that, to the right of n0 the
f(n) always lies on or below c*g(n).
O(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤
f(n) ≤ c g(n), for all n ≥ n0}
Big-Omega (Ω) notation gives a lower bound for a function f(n) to within a constant factor.
We write f(n) = Ω(g(n)), If there are positive constantsn0 and c such that, to the right of n0 the
f(n) always lies on or above c*g(n).
Ω(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ c g(n) ≤ f(n), for all n ≥
n0}
We write f(n) = Θ(g(n)), If there are positive constantsn0 and c1 and c2 such that, to the right
of n0 the f(n) always lies between c1*g(n) and c2*g(n) inclusive.
Θ(g(n)) = {f(n) : There exist positive constant c1, c2 and n0 such that 0 ≤ c1 g(n) ≤ f(n) ≤ c2
g(n), for all n ≥ n0}
⮚ Bubble sort is a sorting algorithm that operates by going through the list to be sorted
repeatedly while comparing pairs of elements that are adjacent.
⮚ If a pair of elements is in the wrong order they are swapped to place them in the correct
order. This traversal is repeated until no further swaps are required (which means that the
list is sorted).
⮚ Since the smaller elements in the list come to the top as a bubble comes to the surface, it is
given the name bubble sort.
⮚ Bubble sort is a very simple sorting algorithm but it has an average case time complexity of
O(n2) when sorting a list with n elements.
⮚ Due to this, bubble sort is not suitable for sorting lists with a large number of elements.
⮚ But due its simplicity, bubble sort is taught during introductions to algorithms.
Insertion Sort
⮚ Insertion sort is another sorting algorithm, which operates by inserting an element in the
input list into the correct position in a list (that is already sorted).
⮚ This process is applied repeatedly until the list is sorted. In insertion sort, sorting is carried
out in-place.
⮚ Therefore after the ith iteration of the algorithm, the first i+1 entries in the list will be sorted
and the rest of the list will be unsorted.
⮚ At each iteration, the first element in the unsorted part of the list will be taken and inserted
into the correct place in the sorted section of the list.
⮚ Due to this, insertion sort is also not suitable for sorting large lists.
8 .a. Implement a program to read N students names, store them in an array and sort them in
alphabetical order. Output the sorted names.[L3][7]
#include <stdio.h>
#include <string.h>
int main()
{
inti, j, num;
char name[20][20], temp[20];
printf("Enter number of students names to be sorted in alphabetical order: ");
scanf("%d", &num);
printf("Enter students name : \n", num);
for(i=0; i<num; i++)
{
scanf("%s",name[i]);
}
for(i=0; i< num-1 ; i++)
{
for(j=i+1; j<num; j++)
{
if(strcmp(name[i],name[j]) > 0)
{
strcpy(temp,name[i]); strcpy(name[i],name[j]); strcpy(name[j],temp);
}
}
}
printf("Students Names after sorting in alphabetical order: \n"); for(i=0; i<num ; i++)
{
printf("%s\n",name[i]);
}
}
Expected Output:
Dolphin
Jwala
Rani
Sony
8 b. Explain the algorithm for QUICK sort and give a suitable example. Quick sort is based
on partition. [L4][CO4] [8]
It is also known as partition exchange sorting. The basic concept of quicksort process is to
pick one element from an array and rearrange the remaining elements around it. This
element divides the main list into two sub lists. This chosen element is called pivot. Once
pivot is chosen, then it shifts all the elements less than pivot to left of value pivot and
all the elements greater than pivot are shifted to the right side. This procedure of choosing
pivot and partitioning the list is applied recursively until sub-lists consist of only one
element.
Ex:- A list of unsorted elements are: 8 3 2 11 5 14 0 2 9 4 20
Algorithm for quick sort: It is also known as partition exchange sort. It was invented by CAR
Hoare. It is based on partitions. The basic concept of a quick sort process is to pick one element
from an array and rearrange the remaining elements around it.
This element divides the main list into two sub lists.
This chosen element is called pivot.
Once pivot is chosen, then it shifts all the elements less than pivot to the left of the value pivot and
all the elements greater than pivot are shifted to the right side.
This procedure of choosing pivot and partition the list is applied recursively until sub-lists
consisting of only one element.
quicksort(q) varlist less, pivot
List, greater if length(q) ≤ 1 return q
select a pivot value pivot from q for each x in q except the pivot element
if x < pivot then add x to less
if x ≥ pivot then add x to greater add pivot to pivot
List return concatenate(quicksort(less), pivot List, quicksort(greater))
● Best case = fastest time to complete, with optimal inputs chosen.
For example, the best case for a sorting algorithm would be data that's already sorted.
● Worst case = slowest time to complete, with pessimal inputs chosen.
For example, the worst case for a sorting algorithm might be data that's sorted in
reverse order (but it depends on the particular algorithm).
● Average case = arithmetic mean. Run the algorithm many times, using many different
inputs of size n that come from some distribution that generates these inputs (in the
simplest case, all the possible inputs are equally likely), compute the total running time
(by adding the individual times), and divide by the number of trials. You may also need
to normalize the results based on the size of the input sets.
Complexity and running time are often expressed in "Big O notation," which is used to
describe the approximate amount of time an algorithm requires to complete, based on the size
of its input.
9. a. Explain the algorithm for Merge sort and give a suitable example.[L3][CO4] [7]
The basic concept of merge sort divides the list into two smaller sub-lists of approximately equal
size.
Recursively repeat this procedure till only one element is left in the sub-list.After this, various
sorted sub-lists are merged to form sorted parent list. This process goes on recursively till the
original sorted list arrived.
Algorithm for merge sort:
Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time has a lower
order of growth than insertion sort. Since we are dealing with sub-problems, we state each sub-
problem as sorting a sub-array A[p .. r].
Initially, p = 1 and r = n, but these values change as we recurse through sub-problems. To sort
A[p .. r]:
1. Divide Step If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p .. r] into two sub-arrays A[p .. q] and A[q + 1 .. r], each containing about half
of the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step Conquer by recursively sorting the two sub-arrays A[p .. q] and A[q + 1 .. r].
3. Combine Step Combine the elements back in A[p .. r] by merging the two sorted sub-arrays
A[p .. q] and A[q + 1 .. r] into a sorted sequence.
9. b. Explain a sorting technique which follows the divide and conquer mechanism with an
example. [L3][CO4] [8]
Divide and Conquer:- This is a special case of recursion in which a given problem is divided into
two or more sub-problems of exactly the same type and the solution to the problem is expressed in
terms of solution to sub-problem. i.e. Dividing the list of elements into two approximately equal
parts recursively and finding solutions independently then merged together into a single list.
Quick and merge sorts are based on the Divide and Conquer concept. The divide and conquer
strategy solves a problem by :
1. Breaking into subproblems that are themselves smaller instances of the same type of problem.
2. Recursively solving these sub problems.
3. Appropriately combining their answers.
Two types of sorting algorithms which are based on this divide and conquer algorithm :
1. Quick sort: Quick sort also uses few comparisons (somewhat more than the other two). Like
heap sort it can sort "in place" by moving data in an array.
2. Merge sort: Merge sort is good for data that's too big to have in memory at once, because its
pattern of storage access is very regular. It also uses even fewer comparisons than heap sort, and is
especially suited for data stored as linked lists.
10. a. Write the implementation of merge sort with example in detail? [L3][CO4] [10]
#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0; /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */
while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}
Working of Merge sort Algorithm
Now, let's see the working of merge sort Algorithm.
To understand the working of the merge sort algorithm, let's take an unsorted array. It will be easier
to understand the merge sort via an example.
Let the elements of array are -
According to the merge sort, first divide the given array into two equal halves. Merge sort keeps
dividing the list into equal parts until it cannot be further divided.
As there are eight elements in the given array, so it is divided into two arrays of size 4.
Now, again divide these two arrays into halves. As they are of size 4, so divide them into new
arrays of size 2.
Now, again divide these arrays to get the atomic value that cannot be further divided.
In the next iteration of combining, now compare the arrays with two data values and merge them
into an array of found values in sorted order.
Now, there is a final merging of the arrays. After the final merging of above arrays, the array will
look like -