- 分治策略
分治策略就是将一个问题分解成很多小问题,递归求解,然后将每个小问题的解“组合”在一起,问题就被解决了。 - 归并排序
归并排序就是利用了分治策略。思想如下图所示:
- 代码如下:
public class MergeSort {
public static void main(String[] args) {
int[] array = {8,4,5,7,1};
int[] temp = new int[array.length];
mergeSort(array,0,array.length-1,temp);
System.out.println(Arrays.toString(array));
}
public static void mergeSort(int[] array, int left, int right, int[] temp){
if (left<right){
int mid = (left+right)/2;
mergeSort(array,left,mid,temp);
mergeSort(array,mid+1,right,temp);
merge(array,left,mid,right,temp);
}
}
public static void merge(int[] array, int left, int mid, int right, int[] temp){
int i = left;
int j = mid+1;
int t = 0;
while (i<=mid && j<=right){
if (array[i]<=array[j]){
temp[t] = array[i];
t++;
i++;
}
else {
temp[t] = array[j];
t++;
j++;
}
}
while (i<=mid){
temp[t] = array[i];
t++;
i++;
}
while (j<=right){
temp[t] = array[j];
t++;
j++;
}
t = 0 ;
int tempLeft = left;
while (tempLeft<=right){
array[tempLeft] = temp[t];
tempLeft++;
t++;
}
}
}