归并排序

来源:互联网 发布:淘宝手柄 编辑:程序博客网 时间:2024/04/27 11:02
public class MergeSort {

public static void main(String[] args)
{
int a[]={1,3,0,5,6};
MergeSort ms=new MergeSort();
ms.sort (a,0,4);

for (int i=0;i<a.length;i++)
System.out.println(a[i]);
}

public void sort(int a[],int low,int high)
{
if (low<high)
{
int mid=(low+high)/2;
 
sort(a,low,mid);
sort(a,mid+1,high);
mergesort(a,low,high,mid);
 
 
}




}

public void mergesort(int a[],int low,int high,int mid)
{


int c[]=new int [a.length];
int lowtemp=low;
int midtemp=mid+1;


int tempadr=low;
int tmp=low;


while (lowtemp<=mid&&midtemp<=high)
{
if (a[lowtemp]<=a[midtemp])
c[tempadr++]=a[lowtemp++];
else 
c[tempadr++]=a[midtemp++];


}


while (midtemp<=high)
c[tempadr++]=a[midtemp++];
 
while(lowtemp<=mid)
c[tempadr++]=a[lowtemp++];
 
for (int i=low;i<=high;i++)
a[i]=c[i];

System.out.println(Arrays.toString(a));
 


}






}
0 0
原创粉丝点击