本文共 1656 字,大约阅读时间需要 5 分钟。
import java.util.Arrays;//归并排序 递归版:分而治之//时间复杂度:n*log2n//空间复杂度:O(n)//稳定性:稳定的public class mergeTest { public static void mergeSort(int[] array){ mergeSortInternal(array,0,array.length-1); } //递归 private static void mergeSortInternal(int[] array, int low, int high){ if(low>=high){ return; } int mid=(low+high)/2; //递归左边 mergeSortInternal(array,low,mid); //递归右边 mergeSortInternal(array,mid+1,high); //合并 merge(array,low,mid,high); } //合并 public static void merge(int[] array,int low,int mid,int high){ int s1=low; int s2=mid+1; //申请一个新的数组,长度为high-low+1 int[] tempArray=new int[high-low+1]; //tempArray的数组下标 int i=0; //1、当两个归并段都有数据 while(s1<=mid && s2<=high){ if(array[s1]<=array[s2]){ tempArray[i++]=array[s1++]; }else{ tempArray[i++]=array[s2++]; } } //2、有一个归并段已经走完 while (s1<=mid){ tempArray[i++]=array[s1++]; } while (s2<=high){ tempArray[i++]=array[s2++]; } //将tempArray的有序数据放回原来数组里面 for (int j = 0; j
在这import java.util.Arrays;//归并排序 非递归版本public class mergeTest1 { public static void mergeSort(int[] array) { for (int i = 1; i < array.length; i *= 2) { merge(array,i); } } //gap代表每个归并段的数据 public static void merge(int[] array,int gap){ //申请一个新的数组 int[] tempArray=new int[array.length]; //标志新数组的下标 int k=0; int s1=0; int e1=s1+gap-1; int s2=e1+1; int e2=s2+gap-1
转载地址:http://tbrnz.baihongyu.com/