归并排序
算法思想:假设初始序列含有n个记录,首先将这n个记录看成n个有序的子序列,每个子序列的长度为1,然后凉凉合并,得到[n/2]个长度为2的有序子序列。
在次基础上,在对长度为2的有序子序列进行两两归并,得到若干个长度为4的有序子序列。如此重复,知道得到一个长度为n的有序序列为止。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package paixu;
import java.util.Arrays;
public class PaiXu {
public static void main(String[] args) {
int []a={48,62,35,77,55,14,35,98,0};
Msort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
//使用递归的方法可实现排序
public static void Msort(int[] a,int low,int high){
int mid=(low+high)/2;
if(low<high){
Msort(a,low,mid);
Msort(a,mid+1,high);
Merge(a,low,mid,high);
}
}
public static void Merge(int[] a,int low,int mid,int high) {
int []temp=new int[high-low+1];//临时变量,存放排好序的数组
int i=low;
int j=mid+1;
int index=0;
while(i<=mid&&j<=high){
if(a[i]<=a[j]){
temp[index]=a[i];
i++;
}
else{
temp[index]=a[j];
j++;
}
index++;
}
while(j<=high){ //前面的序列都已排完序,而后面的序列还有剩下的元素
temp[index]=a[j];
index++;
j++;
}
while(i<=mid){ //后面的序列都已排完序而前面的序列还有剩下的元素
temp[index]=a[i];
index++;
i++;
}
for(int k=0;k<temp.length;k++){ //将临时数组中的元素放入a数组中
a[k+low]=temp[k];
}
}
}