package com.datastructure.sortingalgorithm;
import java.util.Arrays;
/**
* 归并排序
*/
public class MergeSort {
public static void main(String[] args) {
int[] a = {90,-2,0,1,2,90,5,-2,4,3};
mergeSort(a,0,a.length-1,new int[a.length]);
System.out.println(Arrays.toString(a));
}
//拆分加归并
public static void mergeSort(int[] arr,int left,int right,int[] temp){
if (left<right){
int mid = (left + right)/2;
//向左递归分解
mergeSort(arr,left,mid,temp);
//向右递归分解
mergeSort(arr,mid+1,right,temp);
//合并
merge(arr,left,mid,right,temp);
}
}
//归并
public static void merge(int[] arr,int left,int mid,int right,int[] temp){
int i = left;//左边数组的初始索引
int j = mid+1;//右边数组的初始索引
int t = 0;//指向temp数组的当前索引
//先把左右两边(有序)的数据按照规则填充到temp数组
//知道左右两边的有序列表,有一边处理完毕为止
while (i<=mid && j<=right){
if (arr[i]<=arr[j]){
temp[t] = arr[i];
t++;
i++;
}else {
temp[t] = arr[j];
j++;
t++;
}
}
//把所有剩余的数据全部填充到temp中
while (i<=mid){
temp[t] = arr[i];
t++;
i++;
}
while (j<=right){
temp[t] = arr[j];
j++;
t++;
}
//将temp数据拷贝到arr
t=0;
int arrLeft = left;
while (arrLeft<=right){
arr[arrLeft] = temp[t];
t++;
arrLeft++;
}
}
}
归并排序
最新推荐文章于 2020-06-19 18:09:29 发布