特点:稳定,不需要交换相同的元素。
什么情况使用归并排序?
假设有一个已经按照职位排序的员工列表,现在要按照工资排序。若两个员工工资相等,此时采用归并排序(稳定),将会保留职位排列的顺序。即首先按照工资排序,工资同者按职位排序。
package 算法;
public class 归并 {
public void sort(int[] a,int left,int right) {//递归调用,将数组不断二分至最小单元
int mid=(left+right)/2;
if(left<right) {
sort(a,left,mid);//先迭代左半边
sort(a,mid+1,right);//后迭代右半边
merge(a,left,mid,right);//迭代完了,合并排好序的两个最小单元
}
}
public void merge(int[] a,int left,int mid,int right) {//合并两个排好序的最小单元合并排序
int k=left;//之前设置k=0,错误,因为直接在数组a上调整,传导来的参数为a上实际位置而不是
//真正分割数组
int[] temp =new int[a.length];
int p1=left;
int p2=mid+1;
while(p1<=mid&&p2<=right) {//不超过两个单元的最右边
if(a[p1]<=a[p2]) {
temp[k++]=a[p1++];
}else {
temp[k++]=a[p2++];
}
}
while(p1<=mid) {//右边超即右边都放入了temp,此时把左边放入temp
temp[k++]=a[p1++];
}
while(p2<=right) {
temp[k++]=a[p2++];
}
for(int i=left;i<=right;i++)
a[i]=temp[i];
}
public static void main(String[] args) {
归并 a=new 归并();
int [] arr= {9,6,8,4,7,3,1};
a.sort(arr, 0, arr.length-1);
for(int aa:arr)
System.out.println(aa);
}
}