0% found this document useful (0 votes)
48 views

Unit 4 Que & Ans

Selection sort works by dividing a list into a sorted and unsorted sub-list, separated by an imaginary wall. It finds the smallest element in the unsorted sub-list and swaps it with the element at the start of the unsorted sub-list, effectively moving the wall one element to the right. This process is repeated by finding the next smallest element in the unsorted sub-list and swapping it with the element at the start. This continues until the entire list is sorted after n-1 passes through the list.

Uploaded by

Vathyasam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Unit 4 Que & Ans

Selection sort works by dividing a list into a sorted and unsorted sub-list, separated by an imaginary wall. It finds the smallest element in the unsorted sub-list and swaps it with the element at the start of the unsorted sub-list, effectively moving the wall one element to the right. This process is repeated by finding the next smallest element in the unsorted sub-list and swapping it with the element at the start. This continues until the entire list is sorted after n-1 passes through the list.

Uploaded by

Vathyasam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Unit 4

1a. Define Sorting? Explain the complexities of selection, insertion and bubble sort?
[L2][CO5] [marks 7]
Ans:

Sorting is a technique to rearrange the elements of a list in ascending or descending order,


which can be numerical, lexicographical, or any user-defined order. Sorting is a process
through which the data is arranged in ascending or descending order

● 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 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

● Worst case performance: O(n2)


● Best case performance: O(n2)
● Average case performance: O(n2)
● Worst case space complexity: O(n) total, O(1) auxiliary

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

● 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 is not a practical sorting algorithm when n is large.

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];

printf("Enter number of elements to be sorted: ");

scanf("%d",&n);

printf("\nEnterelements of array: ");

for(i=0 ; i<n ; i++)


{

scanf("%d",&arr[i]);

bubblesort(arr,n);

void bubblesort(intarr[],int n)

inti,j,temp;
for(i=0 ; i<n ; i++)

for(j=0 ; j<n-i-1 ; j++)

if(arr[j]>arr[j+1]) //Swapping Condition is Checked

temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

} }}

printf("The Sorted Array is: ");

for(i=0 ; i<n ; i++)

printf(" %4d",arr[i]);

}
}

Expected Output:

Enter number of elements to be sorted: 5

Enter elements of array: 36 5 4 3 2


The Sorted Array is: 2 3 4 5 36
2 .a. Explain a program that uses non recursive function to sort the given list of
integers in descending using selection sort. Trace your program with the following
inputs and sort them in descending order: 20 12 10 15 2 ? [L3][CO4] [ 8]

#include<stdio.h>

void selectionsort(int [],int);

void main()

inti,n,temp,j,arr[25];

printf("Enter number of elements to be sorted: ");

scanf("%d",&n);

printf("\nEnter elements of array: ");

for(i=0 ; i<n ; i++)

scanf("%d",&arr[i]);

selectionsort(arr,n);

void selectionsort(intarr[],int n)

inti,j,max,temp;

for(i=0 ; i<n ; i++)

max=i;

for(j=i+1 ; j<n ; j++)

if(arr[max]<arr[j]) //Swapping Condition is Checked

{
max=j;

}}

if(max!=i)

temp=arr[i];
arr[i]=arr[max]; arr[max]=temp;
}}

printf("The Sorted Array is: ");

for(i=0 ; i<n ; i++)

printf(" %d",arr[i]);

}}

Expected output:

Enter number of elements to be sorted: 4

Enter elements of array: 1 2 3 4

The Sorted Array is: 4 3 2 1

Working of Selection Sort

1. Set the first element as minimum. Select


first element as minimum
2. Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum.

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.

Swap the first with minimum


4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated
until all the elements are placed at their correct positions.

The first iteration


The second iteration
The third iteration

The fourth iteration

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];

printf("Enter number of elements:


"); scanf("%d", &n);

printf("Enter %d integers :", n);


for (i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i<= n - 1; i++)
{
key=arr[i];
j = i-1;
while (j >= 0 &&arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}

printf("Array of integers using insertion sort in Ascending Order: ");


for (i = 0; i<= n - 1; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Enter number of elements: 5
Enter 5 integers :7 4 5 8 2
Array of integers using insertion sort in Ascending Order: 2 4 5 7 8

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)

Step 1 : Repeat For K = 0 to N – 2 Begin


Step 2 : Set POS = K

Step 3 : Repeat for J = K + 1 to N – 1 Begin

If A[ J ] < A [ POS ]

Set POS = J

End For

Step 5 : Swap A [ K ] with A [ POS ]

End For

Step 6 : Exit

Ex:- A list of unsorted elements are: 23 78 45 8 32 56

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]

3. {Put A[j] into the sorted sequence A[1 . . j − 1]}

4. i ← j − 1

5. WHILE i> 0 and A[i] > key

6. DO A[i +1] ← A[i]

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;

printf("Enter the size of an array : ");


scanf("%d", &n);
printf("Enter the array elements: ");
for(i = 0; i< n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element: ");
scanf("%d", &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.

5 a. What is searching? Distinguish between linear and binary search? [L4][CO4]


[7]

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:

● Linear Search or Sequential Search


● Binary Search
Linear Search or Sequential Search in C Language to find whether a value exists in a given
array. If it exists then return to the current position. In this algorithm we check the value one
by one in a given list. The time complexity of the above algorithm is O(n). It takes more time
than Binary Search.

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).

Key Differences Between Linear Search and Binary Search

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:

Step 1: set-up a flag to indicate “element not found”

Step 2: Take the first element in the list

Step 3: If the element in the list is equal to the desired

element Set flag to “element found”

Display the message “element found in the list”

Go to step 6

Step 4: If it is not the end of list,

Take the next element in the list

Go to step 3
Step 5: If the flag is “element not found”

Display the message “element not found”

Step 6: End of the Algorithm

Advantages:

1. It is a simple and conventional method of searching data. The linear or sequential name

implies that the items are stored in a systematic manner.

2. The elements in the list can be in any order. i.e. The linear search can be applied on sorted
or

unsorted linear data structure.

Disadvantage:

1. This method is insufficient when a large number of elements is present in the list.

2. It consumes more time and reduces the retrieval rate of the

system. Time complexity: O(n)

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:

● Linear Search or Sequential Search


● Binary Search

● 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 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)

Binary Search Time Complexity

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.

And the above steps continue till beg<end

Best case could be the case where the first mid-value get matched to the element to be
searched

● Best Time Complexity: O(1)


● Average Time Complexity: O(logn)
● Worst Time Complexity: O(logn)
● Space complexity: O(1)

7. a. Discuss about best, average, worst case complexities? [L2] [CO5][ 6]

7. b. Distinguish between selection sort and insertion sort. [L4][CO4] [ 9]

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

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}

Big Theta Notation


Big-Theta(Θ) notation gives bound for a function f(n) to within a constant factor.

● Best case = Big Oh Notation


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 =Big theta notation
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 = big omega notations
● 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.

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}

DIFFERENCE BETWEEN BUBBLE SORT AND INSERTION SORT


bubble sort

⮚ 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.

⮚ nsertion sort has an average case time complexity of O(n2).

⮚ 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:

Enter number of students names to be sorted in alphabetical order: 5


Enter students name :
Jwala Rani Sony Bunny Dolphin
Students Names after sorting in alphabetical order:
Bunny

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.

Time Complexity of Quick sort:


Best case : O (n log n)
Average case : O (n log n)
Worst case : O (n2)
Advantages of quick sort:
1.This is the fastest sorting method among all.
2. Its efficiency is also relatively good
3. It requires a relatively small amount of memory.
Disadvantages of quick sort: 1. It is a complex method of sorting, so it is a little harder to
implement than other sorting methods.

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.

To accomplish this step, we will define a procedure MERGE (A, p, q, r).


Note that the recursion bottoms out when the sub-array has just one element, so that it is trivially
sorted.
To sort the entire sequence A[1 .. n], make the initial call to the procedure
MERGE-SORT (A, 1, n). MERGE-SORT (A, p, r)

1. IF p < r // Check for base case


2. THEN q = FLOOR[(p + r)/2] // Divide step 3.
3. MERGE (A, p, q) // Conquer step. 4.
4. MERGE (A, q + 1, r) // Conquer step. 5.
5. MERGE (A, p, q, r) // Conquer step.

Time Complexity of merge sort:


Best case : O (n log n)
Average case : O (n log n)
Worst case : O (n log n)

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.

Note: explain about quick sort

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.

Now, combine them in the same manner they were broken.


In combining, first compare the element of each array and then combine them into another array in
sorted order.
So, first compare 12 and 31, both are in sorted positions. Then compare 25 and 8, and in the list of
two values, put 8 first followed by 25. Then compare 32 and 17, sort them and put 17 first followed
by 32. After that, compare 40 and 42, and place them sequentially.

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 -

Now, the array is completely sorted..

10. b. write a program for implementation of quick sort?[L4][CO4][5]


#include <stdio.h>  
/* function that consider last element as pivot, place the pivot at its exact position, and place
smaller elements to left of pivot and greater elements to right of pivot.  */  
int partition (int a[], int start, int end)  
{  
    int pivot = a[end]; // pivot element  
    int i = (start - 1);  
  
    for (int j = start; j <= end - 1; j++)  
    {  
        // If current element is smaller than the pivot  
        if (a[j] < pivot)  
        {  
            i++; // increment index of smaller element  
            int t = a[i];  
            a[i] = a[j];  
            a[j] = t;  
        }  
    }  
    int t = a[i+1];  
    a[i+1] = a[end];  
    a[end] = t;  
    return (i + 1);  
}  
  
/* function to implement quick sort */  
void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending 
index */  
{  
    if (start < end)  
    {  
        int p = partition(a, start, end); //p is the partitioning index  
        quick(a, start, p - 1);  
        quick(a, p + 1, end);  
    }  
}  
  
/* function to print an array */  
void printArr(int a[], int n)  
{  
    int i;  
    for (i = 0; i < n; i++)  
        printf("%d ", a[i]);  
}  
int main()  
{  
    int a[] = { 24, 9, 29, 14, 19, 27 };  
    int n = sizeof(a) / sizeof(a[0]);  
    printf("Before sorting array elements are - \n");  
    printArr(a, n);  
    quick(a, 0, n - 1);  
    printf("\nAfter sorting array elements are - \n");    
    printArr(a, n);  
      
    return 0; 
}

You might also like