算法思路:
归并:先"归"后"并"
1.核心思路:将两个有序的数组和并成一个
aux[]:存放临时的数据
merge(a,low,mid,high):将数组a从low到mid这一段,以及从mid+1到high这一段合并
定义两个指针i和j,i指向low,j指向mid+1,同时往后遍历,将较小的放在aux指定位置,直到i或者j有一个走到了尽头。然后将另一也走向尽头并放入aux后面,此时aux即为最后的排序结果,将其复制回原来的a即可。
注:由于是递归low>=high要退出循环
public class MergeSort { private int[] aux; @Test public void test(){ int[] a = {1,2,5,8,3,4,6,9,7}; aux = new int[a.length]; sort(a,0,a.length-1); System.out.println(Arrays.toString(a)); } public void sort(int[] a, int low, int high){ int mid = (low+high)/2; if(low>=high){ return; } sort(a, low, mid); sort(a, mid + 1, high); merge(a, low, mid, high); } /** * 将两个有序的数组合并为一个有序的数组,两个数组分别是low-mid ,mid+1-high */ private void merge(int[] a, int low, int mid, int high) { // 左右指针i j int i=low,j=mid+1; // aux指针 int k; for(k=low;i<=mid && j<=high;){ if(a[i]<a[j]){ aux[k++] = a[i++]; }else{ aux[k++] = a[j++]; } } while(i<=mid){ aux[k++] = a[i++]; } while(j<=high){ aux[k++] = a[j++]; } for(int n=low;n<=high;n++){ a[n] = aux[n]; } } }