package mergesort;
import java.util.Arrays;
public class MergeSort {
public static void mergesort(int[] data,int start,int end){
//左闭右开固定写法
/*
* 如果写成这样:mergesort(data,mid,end)
* 这样将导致递归后start的值发生变化,引发错误!
* */
if(start+1 == end){
return;
}
int mid = (start+end)/2;//取中值
mergesort(data,start,mid);//将数组分拆分为两部分
mergesort(data,mid,end);
int i = start;
int j = mid;
int k = 0;
int[] temp = new int[end-start];//创建临时数组
//将data数组赋值给临时数组temp排序
while (i<mid && j<end){
if(data[i]<=data[j]){
temp[k++] = data[i++];
}else{
temp[k++] = data[j++];
}
}
//处理当一侧数组已经赋值完毕但另一次没复制完毕情况;
if(i< mid){
while(i<mid){
temp[k++] = data[i++];
}
}else {
while(j<end){
temp[k++] = data[j++];
}
}
//将有序的temp数组赋值给data数组
for(int l =0;l<end-start;l++){
data[start+l]=temp[l];
}
System.out.println(Arrays.toString(data));
}
public static void main(String[] args) {
int[] data = new int[]{2,5,4,9,7,4,5,1,3};
System.out.print("排序前:");
System.out.println(Arrays.toString(data));
mergesort(data,0,data.length);
System.out.print("排序后:");
System.out.println(Arrays.toString(data));
}
}
归并排序java
最新推荐文章于 2024-01-04 20:00:05 发布