package cn.ustc.sort;public class MergeSort {

public static void main(String[] args) {
int[] a = {4,2,8};
for(int i=0;i<a.length;i++){
System.out.print(a[i]);
}
mergeSort(a,0,2);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}

public static void merge(int array[], int low, int mid, int high)
{
int i, k;
int[] temp = new int[array.length];
int begin1 = low;
int end1 = mid;
int begin2 = mid + 1;
int end2 = high;
 
for (k = 0; begin1 <= end1 && begin2 <= end2; ++k)  //比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
if(array[begin1]<=array[begin2])
temp[k] = array[begin1++];
else
temp[k] = array[begin2++];
while(begin1<=end1) //若第一个序列有剩余,直接拷贝出来粘到合并序列尾
temp[k++] = array[begin1++];
while(begin2<=end2) //若第二个序列有剩余,直接拷贝出来粘到合并序列尾
temp[k++] = array[begin2++];
for (i = 0; i < (high-low+1); i++) //将排序好的序列拷贝回数组中
array[low+i] = temp[i];
} public static void mergeSort(int[] array,int first,int last) {
int mid = 0;
while(first<last) {
mid = (first+last)/2;
mergeSort(array,first,mid);
mergeSort(array,mid+1,last);
merge(array,first,mid,last);
}
}

}

解决方案 »

  1.   

    while(first<last) {  改成 if(first<last) {就可以了
    完整代码如下
    public class MergeSort{
    public static void main(String[] args){
    int[] a={4,2,8,12,3,0,-1,-100,-200,400,100,3,5,6,8,2,1};
    for(int i=0;i < a.length;i++){
    System.out.print(a[i]+" ");
    }
    System.out.println();
    mergeSort(a,0,a.length-1);
    for(int i=0;i < a.length;i++){
    System.out.println(a[i]);
    }
    } public static void merge(int array[],int low,int mid,int high){
    int i,k;
    int[] temp=new int[array.length];
    int begin1=low;
    int end1=mid;
    int begin2=mid + 1;
    int end2=high; for(k=0;begin1 <= end1 && begin2 <= end2;++k)
    // 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
    if(array[begin1] <= array[begin2])
    temp[k]=array[begin1++];
    else
    temp[k]=array[begin2++];
    while(begin1 <= end1)
    // 若第一个序列有剩余,直接拷贝出来粘到合并序列尾
    temp[k++]=array[begin1++];
    while(begin2 <= end2)
    // 若第二个序列有剩余,直接拷贝出来粘到合并序列尾
    temp[k++]=array[begin2++];
    for(i=0;i < (high - low + 1);i++)
    // 将排序好的序列拷贝回数组中
    array[low + i]=temp[i];
    } public static void mergeSort(int[] array,int first,int last){
    int mid=0;
    if(first < last){
    mid=(first + last) / 2;
    mergeSort(array,first,mid);
    mergeSort(array,mid + 1,last);
    merge(array,first,mid,last);
    }
    }
    }
      

  2.   

    死循环啦:
    看代码 while(first < last){ 中, first和last的值都不会变, 所以first<last=true,那么它就会一直=true, 就陷入死循环了