Lab 01
Lab 01
Lab 01
LAB REPORT NO 01
Course Title: Algorithms Lab
Course Code: CSE 206 Section:D1
Student Details
Name ID
Lab Date:24-10-2022
Submission Date: 31-10-2022
Course Teacher’s Name : Tanoy Debnath
[For Teachers use only: Don’t Write Anything inside this box]
2. OBJECTIVES/AIM
Merge Sort
In the merge sort, the array is parted into just 2 halves (i.e. n/2).
It operates fine on any size of array.
It has a consistent speed on any size of data.
Quick Sort
The splitting of an array of elements is in any ratio, not necessarily divided into half.
It works well on smaller arrays.
It works faster than other sorting algorithms for small data sets like Selection sort
etc.
Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in
the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list
respectively.
4. IMPLEMENTATION
Merge Sort Algorithm
#include <stdio.h>
void mergesort();
void marge();
int main() {
int a [40],n,i;
printf("Enter Size of array::");
scanf("%d",&n);
printf("Enter Elements:::");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
return 0;
}
void mergesort(int a[],int first,int last){
int mid;
if(first<last){
mid=(first+last)/2;
mergesort(a,first,mid);
mergesort(a,mid+1,last);
marge(a,first,mid,last);
}
}
i=first;
j=mid+1;
k=first;
while(i<=mid&&j<=last){
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
if(i>mid){
while (j<=last)
b[k++]=a[j++];
}
else
{
while (i<=mid)
b[k++]=a[i++];
}
for(i=first;i<=last;i++)
a[i]=b[i];
}
Quick Sort Algorithm
#include <stdio.h>
}
}
temp=a[p];
a[p]=a[j];
a[j]=temp;
quiksort(a,0,j-1);
quiksort(a,j+1,last);
}
}
int main()
{
int a[40],n,i;
printf("Enter size of arr::");
scanf("%d",&n);
printf("Enter Elements:::");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quiksort(a,0,n-1);
Although both merge sort and quicksort work on the same divide-and-conquer principle,
they handle the partition and sorting very differently.
Merge sort partitions a list into two sublists of equal sizes (different in size by 1, when
the size of the list is odd) and merges the sorted sublists optimally to form a sorted list.
In contrast, quicksort doesn’t necessarily partition the list into sublists of equal size. The
partition sizes may be of any size, depending on how we choose the pivot.
We can also observe that merge sort performs all the sorting during the process of
merging while quicksort performs most of the sorting in the process of dividing.