import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] a={20,1,3,8,5,9,4,25};
mergeSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
public static void mergeSort(int[] a,int first,int last){
int len=a.length;
if(first>=last)return;
if(first<last){
//int mid=(first+last)/2;
//to avoid overflow,you should do it like this:
int mid=(first&last)+((first^last)>>1);
int[] temp=new int[len];
mergeSort(a,first,mid);
mergeSort(a,mid+1,last);
mergeTwoArray(temp,a,first,mid,last);
}
}
public static void mergeTwoArray(int[] temp,int[] a,int first,int mid,int last){
int i=first;
int j=mid+1;
int k=0;
while(i<=mid&&j<=last){
if(a[i]<a[j]){
temp[k]=a[i];
i++;
}else{
temp[k]=a[j];
j++;
}
k++;
}
while(i<=mid){
temp[k++]=a[i++];
}
while(j<=last){
temp[k++]=a[j++];
}
//System.arraycopy(src, srcPos, dest, destPos, length);
//at first,i write it like this :
//System.arraycopy(temp, 0, a, 0, temp.length);
//I can't get it right until I do it like this:
System.arraycopy(temp, 0, a, first, last-first+1);
//System.arraycopy(temp, 0, a, first, k);//it also works
}
}
分享到:
相关推荐
java代码-使用java解决java排序之-归并排序的问题的源代码 ——学习参考资料:仅用于个人学习使用!
详解Java常用排序算法-归并排序
java 实现归并排序,有代码实现,复杂度分析,基本步骤,适合初学者吧,
算法-归并排序(java)(csdn)————程序
该资源提供了一份全面的指南,介绍了如何在Java中实现归并排序。文档中涵盖了归并排序的基本概念,包括如何对数组进行排序以及如何在Java中实现归并排序。此外,文档还包括一个逐步指南,介绍如何在Java中实现归并...
实现归并排序的一个类
java代码-归并排序-Java
使用Java实现简单的归并排序算法,给大家提供一个参考。
Java代码-排序-直接插入排序、希尔排序、直接选择排序、冒泡排序、堆排序、快速排序、归并排序中部分排序以及算法-贪心法,大家可以将源码下载下来进行学习,附带着注释和解释,有不理解的可以找博主一起探讨,共同...
java代码-归并排序-----
java代码-小和问题-归并排序扩展
归并排序 在排序前,先建好一个长度等于原数组长度的临时数组
Java实现归并排序.rar
一年前做的排序动画,归并排序动画一直未完成,今天完成了,与大家共享