排序算法之归并算法
算法描述;
归并排序是建立在归并操作上的一种有效算法,该算法是采用分治法,将有序的子序列合并,得到完全有序的序列,即先使每个子序列有序,在使子序列段间有序,将两个有序表合并称为2路归并
算法思路;
首先把长度为n的输入序列分为两个长度为n/2的子序列;
对两个子序列分别采用归并排序;
将两个排序好的子序列合并成一个最终的排序序列.
代码实现;
public class MergeSort{
public static void main(String[] args){
int[] a={12,2,19,96,98,19,3,12,7,45,64};
sort(a);
for(int s: a){
System.out.println(s);
}
}
public static void sort(int[] a){
int[] temp=new int[a.length];
sort(a,0,a.length-1,temp);
System.out.println("执行第一个sort");
}
public static void sort(int[] a,int left,int right,int[] temp){
System.out.println("执行第er个sort");
if(left<right){
int mid=(left+right)/2;
sort(a,left,mid,temp);
sort(a,mid+1,right,temp);
merge(a,left,mid,right,temp);
}
}
public static void merge(int[] a,int left,int mid,int right,int[] temp){
int l=left;
int r=mid+1;
int t=0;
while(l<=mid&&r<=right){
if(a[l]<=a[r]){
temp[t++]=a[l++];
}else{
temp[t++]=a[r++];
}
}
while(l<=mid){
temp[t++]=a[l++];
}
while(r<=right){
temp[t++]=a[r++];
}
t=0;
while(left<=right){
a[left++] = temp[t++];
}
}
}
算法分析
归并排序是一种稳定的排序方法,和选择排序一样,归并排序并不受输入数据的影响,但表现比选择排序好得多,时间复杂度为哦(nlogn)的时间复杂度,代价是需要额外的内存空间