62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.Arrays;
/**分治:
* 1.分解为子问题
* 2.解决
* 3.合并
* 思想:采用分治的思想,一分为2,直至只剩2个数,最后再其合并,完成排序,时间nlogn
* @author Ruixuan
* 第一天:总结算法思路,掌握JavaBug调优
* 自己通过花堆栈调用来理解归并过程的执行,思想到实现会不一样,直接看别人写的代码来写的弊端
*/
public class MergeSort {
public static void mergeSort(int[] a,int left,int right){
int mid = (left + right)/2;
if(left<right){ //递归终止条件
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
merge(a,left,mid,right);
}
Arrays.toString(a);
}
public static void merge(int[] a,int left,int mid,int right){
int temp[] = new int[right - left + 1];
int k = 0;
int i = left;//i是左边待排数组的指针
int j = mid + 1;//j是右边待排的数组指针
while(i<=mid && j<=right){
if(a[i]<a[j])
{
temp[k++] = a[i++];
System.out.println(Arrays.toString(temp));
}
else
{ temp[k++] = a[j++];
System.out.println(Arrays.toString(temp));
}
}
/**
if(i<mid)
while(i<=mid)
temp[k++] = a[i++];
if(j<right)
while(j<=right)
temp[k++] = a[j++];
**/
while(i<=mid)
temp[k++] = a[i++];
while(j<=right)
temp[k++] = a[j++]; //最终是排序错了
for(int num=left,count=0;num<k;num++,count++) //再将排序好的数写回数组,count为遍历temp的指针, *** 排序错误count不能写死为0
{ //从0开始遍历数组是从0到<array.length-1(), 若是num<=k,则多算一次发生数组越界
a[num] = temp[count];
}
}
//错误在这,数值没有改回去
public static void main(String[] args){
int a[] = {3,5,6,2,1,7,4,8};
mergeSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
}
//这里num的范围应该是[left,right],而不是[left,k]
// 自己debug下就很快就知道了
for(int num=left,count=0;num<=right;num++,count++) {
a[num] = temp[count];
}