归并排序就是递归得将原始数组递归对半分隔,直到不能再分(只剩下一个元素)后,开始从最小的数组向上归并排序。
- 将一个数组拆分为两个,从中间点拆开,通过递归操作来实现一层一层拆分。
- 从左右数组中选择小的元素放入到临时空间,并移动下标到下一位置。
- 重复步骤2直到某一下标达到尾部。
- 将另一序列剩下的所有元素依次放入临时空间。
- 将临时空间的数据依次放入原数据数组。
//分 public static void mergeSort(int[] a, int low, int high) { //首先判断 low 和 high是否指向一个地方 if(low >= high) { return; } int mid = (low + high)/2; //先递归左边 mergeSort(a, low, mid); //在递归右边 mergeSort(a, mid+1, high); //合并 merge(a,low,mid,high); System.out.println(Arrays.toString(a)); } //合并 public static void merge(int[] a, int low, int mid, int high) { //定义第一个段的开始 int s1 = low; //定义第二个段的开始 int s2 = mid+1; //定义临时数组 int[] temp = new int[high-low+1]; int i = 0;//定义临时数组的下标 //判断大小将数组放入到临时数组当中去 while(s1<=mid && s2<=high) { if(a[s1] <= a[s2]) { temp[i++] = a[s1++]; }else { temp[i++] = a[s2++]; } } //判断s1当中是否有数据,如果有将其全部拷贝到临死数组当中去 while (s1 <= mid) { temp[i++] = a[s1++]; } //判断s1当中是否有数据,如果有将其全部拷贝到临死数组当中去 while (s2 <= high) { temp[i++] = a[s2++]; } //将临时数组当中的代码放回原数组 for (int j = 0; j < temp.length; j++) { a[j+low] = temp[j]; } }