Friday, June 10, 2016

Merge sort example in core java recursion

Merge Sort:

our final example of recursion is the merge-sort.This is more sorting technique.While the bubble,insertion and selection sort take O(N^2) time.The merge sort is O(N*log N).

Sample Code:

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MergeApp
{
public static void main(String[] args)
{
int[] arrayA={23,47,81,95};
int[] arrayB={7,14,39,55,62,74};
int[] arrayC=new int[10];

merge(arrayA,4,arrayB,6,arrayC);
display(arrayC,10);

}

private static void display(int[] arrayC, int size)
{
for(int j=0;j<size;j++)
System.out.println(arrayC[j] + "  ");
System.out.println(" ");
}

private static void merge(int[] arrayA, int sizeA, int[] arrayB, int sizeB,int[] arrayC)
{
int aDex=0,bDex=0,cDex=0;

while (aDex <sizeA && bDex < sizeB)
if(arrayA[aDex] < arrayA[bDex])
arrayC[cDex++] = arrayA[aDex++];
else
arrayC[cDex++] =arrayB[bDex++];

while(aDex < sizeA)
arrayC[cDex++] =arrayA[aDex++];

while(bDex < sizeB)
arrayC[cDex++] = arrayB[bDex++];
}

}

No comments: