归并排序介绍
归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题分(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)
图解
java代码实现
public class MargetSort {
public static void main(String[] args) {
int arr[] = {5,6,7,2,3,5,6,7,8,1,4,7};
int temp[] = new int[arr.length];
MargeSort(arr,0,11,temp);
System.out.println(Arrays.toString(arr));
}
public static void MargeSort(int[] arr,int left,int right,int[] temp){
if (left<right){
int mid = (left+right)/2;
MargeSort(arr,left,mid,temp);
MargeSort(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; //临时数组的索引
//
while (i<=mid&&j<=right){
if (arr[i]<=arr[j]){
temp[t] = arr[i];
t += 1;
i +=1;
}else{
temp[t] = arr[j];
t += 1;
j +=1;
}
}
//将剩余数据的一边的数据都放到temp
while (i<=mid){
temp[t] = arr [i];
t += 1;
i +=1;
}
while (j<=right){
temp[t] = arr[j];
t += 1;
j +=1;
}
//将temp的数据copy到arr
t= 0;
int tempLeft = left;
while (tempLeft<=right){
arr[tempLeft] = temp[t];
t+=1;
tempLeft+=1;
}
}
}