归并排序

package A;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class JosePhu {
public static void main(String[] args) {
Method method=new Method();
int[] a={1,23,5,6,8,90,5,5,3};
int[] temp=new int[a.length];
method.mergeSort(a,0,a.length-1,temp);
System.out.println(Arrays.toString(a));
}
}

package A;

public class Method {
//这里的任何left和right都只是下标
public void merge(int[] a,int left,int middle,int right,int[] temp){//这是治
System.out.println("一共合并了多少次");
int i=left;
int j=middle+1;
int t=0;
//分为三步,一、先比较排序
while (i<=middle&&j<=right){
if (a[i]<=a[j]){
temp[t]=a[i];
t++;
i++;
}else {
temp[t]=a[j];
t++;
j++;
}
}
//二、将第一步剩下的填充到temp
while (i<=middle){
temp[t]=a[i];
t++;
i++;
}
while (j<=right){
temp[t]=a[j];
t++;
j++;
}
//三、拷贝
t=0;
int templeft=left;
while (templeft<=right){
a[templeft]=temp[t];//注意这里是temp[t],因为要遍历temp
t++;
templeft++;
}
}
public void mergeSort(int[] a,int left,int right,int[] temp){
if (left<right){
int mid=(left+right)/2;
mergeSort(a,left,mid,temp);
mergeSort(a,mid+1,right,temp);//先拆再合(分而治之),这里才是递归,一半一半又一半,直到left==right,即只有一个元素为止
merge(a,left,mid,right,temp);
}
}
}

posted @ 2021-08-01 22:13  朱在春  阅读(34)  评论(0编辑  收藏  举报