Divide-and-conquer Technique
subproblem 2
of size n/2
subproblem 1
of size n/2
a solution to
subproblem 1
a solution to
the original problem
a solution to
subproblem 2
a problem of size n
Using Divide and Conquer:
Mergesort strategy
Sorted
Merge
Sorted Sorted
Sort recursively
by Mergesort
Sort recursively
by Mergesort
first last
(first last)2
Merge Sort Example
6158699 04355886
1586699 3558 0486
Merge
Merge Sort Example
046153558868699
6158699 04355886
Merge
Merge Sort Example
046153558868699
Program
#include<iostream.h>
#include<conio.h>
class MS
{
private:
int A[10];
public:
int n;
int low, high;
void get_data();
void Mergesort(int low, int high);
void Combine(int low, int mid, int high);
void Display();
};
void MS::get_data()
{
cout<<"\n Enter the length of the list";
cin>>n;
cout<<"\n Enter the list elements: \n";
for(int i = 0; i<n; i++)
{
cin>>A[i];
}
}
void MS::Mergesort(int low, int high)
{
int mid;
if(low<high)
{
mid = (low+high)/2; //split the list at mid
Mergesort(low, mid); //first sublist
Mergesort(mid+1, high);//second sublist
Combine(low, mid, high);//merging two sublists
}
}
Program
void MS::Combine(int low, int mid, int high)
{
int i,j,k;
int temp[10];
i = low;
j = mid+1;
k = low;
while(i <= mid && j <= high)
{
if(A[i] <= A[j])
{
temp[k] = A[i];
i++;
k++;
}
else
{
temp[k] = A[j];
j++;
k++;
}
}
while(i<=mid)
{
temp[k] = A[i];
i++;
k++;
}
while(j<=high)
{
temp[k] = A[j];
j++;
k++;
}
for(k = low; k <= high; k++)
{
A[k] = temp[k];
}
}
Program
void MS::Display()
{
cout<<"\n The sorted array is:\n";
for(int i = 0; i<n; i++)
{
cout<<" "<<A[i];
}
}
int main()
{
MS obj;
obj.get_data();
obj.low=0;
obj.high=(obj.n)-1;
obj.Mergesort(obj.low, obj.high);
obj.Display();
getch();
return 0;
}