Merge Sort Algorithm
Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves and then merges the two sorted halves.
The following diagram:
Algorithm:
MergeSort(a[], l, r)
If r > l
- Find the middle point to divide the array into two halves: middle m = (l+r)/2.
- Call mergeSort for the first half: Call mergeSort(a, l, m).
- Call mergeSort for the second half: Call mergeSort(a, m+1, r).
- Merge the two halves sorted in step 2 and 3: Call merge(a, l, m, r).
Source code in Java:
class MergeSort
{
// Merge two subarray of a[].
// First subarray is a[l...m].
// Second subarray is a[m+1....r].
void merge(int a[], int l, int m, int r)
{
int n1 = m-l+1;
int n2 = r-m;
// Create temp array.
int L[] = new int[n1];
int R[] = new int[n2];
// Copy data
for(int i=0;i<n1;i++)
L[i] = a[l+i];
for(int j=0;j<n2;j++)
R[j] = a[m+1+j];
int i= 0, j= 0;
int k = l;
while(i < n1 && j < n2)
{
if(L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
k++;
}
// Copy remaining list of L[] if any
while(i < n1)
{
a[k] = L[i];
i++;
k++;
}
// Copy remaining list of R[] if any
while(i < n2)
{
a[k] = R[j];
j++;
k++;
}
}
// Sort array
void sort(int a[], int l, int r)
{
if(l < r)
{
int m = (l+r)/2;
sort(a, l, m);
sort(a, m+1, r);
// Merge the sorted halves
merge(a, l, m, r);
}
}
static void printArray(int a[])
{
int n = a.length;
int n = a.length;
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println();
}
public static void main(String arg[])
{
int a[] = {29,10,14,37,13};
System.out.println("Given Array);
printArray(a);
MergeSort obj = new MergeSort();
obj.sort(a,0,a.length-1);
System.out.println("\nSorted array");
printArray(a);
}
}
Output:
Given array is
29 10 14 37 13
Sorted array is
10 13 14 29 37
Comments
Post a Comment