Experiment-4 W.A.P To Implement Merge Sort
Experiment-4 W.A.P To Implement Merge Sort
#include <iostream>
using namespace std;
void Merge(int *a, int low, int high, int mid)
{ inti, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;
while (i<= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}
while (i<= mid)
{
temp[k] = a[i];
k++;
i++;
}
while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}
for (i = low; i<= high; i++)
{
a[i] = temp[i-low];
}
}
void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, high, mid);
}
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i< n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
MergeSort(arr, 0, n-1);
cout<<"\nSorted Data ";
for (i = 0; i< n; i++)
cout<<"->"<<arr[i];
return 0;
}
OUTPUT:
TIME COMPLEXITY:
.
Time complexity of Merge Sort is (NlogN) in all 3 cases (worst, average and best) as merge
sort always divides the array in two halves and take linear time to merge two halves.
EXPERIMENT-5
W.A.P TO IMPLEMENT QUICK SORT
CODE:
#include <iostream>
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
int a[50],n,i;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);
if(i<j)
temp=a[i];
a[i]=a[j];
a[j]=temp;
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
OUTPUT:
TIME COMPLEXITY: