Thứ Sáu, 19 tháng 12, 2014

MergeSort

MergeSort program in java

/* Program written by shashi kumar*/
package sortingPackag;

public class MergeSort {

public static void main(String []args)
{

//get The elements for merge sort
int ele[]={11,4,55,6,99,78,0,99,-99};
int re[]=new int[ele.length];
re=merge_sort(ele);
//print res
for(int i=0;i<re.length;i++)
{
System.out.print(re[i]+" ");
}


}
public static int [] merge_sort(int data[])
{
if(data.length<=1)
{
return data;
}
int midpoint=data.length/2;

int left[]=new int[midpoint];
int right[];
int res[]=new int[data.length];
if(data.length%2==0)
{
//even so
right=new int[midpoint];

}
else
{
right=new int[midpoint+1];
}
//copy data values form data to left and right
for(int i=0;i<midpoint;i++)
{
left[i]=data[i];
}
//copy to right
int x=0;
for(int j=midpoint;j<data.length;j++)
{
if(x<data.length)
{
right[x]=data[j];
x=x+1;
}
}
left=merge_sort(left);
right=merge_sort(right);
res=merge(left,right);
return res;
}
public static int [] merge(int left[],int right[])
{
int result[]=new  int[left.length+right.length];
int l=0,r=0,k=0;
while(l<left.length && r<right.length)
{
if(left[l]<right[r])
{
//get minimum from both arrays
result[k]=left[l];
k=k+1;
l=l+1;

}
else
{
result[k]=right[r];
r=r+1;
k=k+1;
}
}
//if not both
while(l<left.length)
{
result[k]=left[l];
l=l+1;
k=k+1;

}
while(r<right.length)
{
result[k]=right[r];
k=k+1;
r=r+1;
}
return result;
}
}


output:
---------------------------

-99 0 4 6 11 55 78 99 99

Không có nhận xét nào:

Đăng nhận xét