归并排序,核心为数组分解和合并的过程。将数组逐渐分解,直到两个两个元素为一组,待小组排序完成后,再将两个两个小组合并为一个一个有序的大组……最后得到排序后的原始数组。
代码实现:
public class MergingSort {
/**
* <p>MethodName:main </p>
* <p>Description:常用排序算法之归并排序 </p>
* <p>@param args</p>
* <p>Return:void </p>
* @author Sunny
* @date 2016-9-27上午10:49:29
*/
public static void main(String[] args) {
int[] arr={7,6,4,9,0,5,2,8,3,1};
mergingSort(arr,0,9);
}
public static void mergingSort(int[] arr,int low,int high){
int mid=(low+high)/2;
if(low<high){
mergingSort(arr,low,mid);
mergingSort(arr,mid+1,high);
merge(arr,low,mid,high);
}
}
public static void merge(int[] arr,int low,int mid,int high){
int[] temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(arr[i]<arr[j]){
temp[k++]=arr[i++];
}else{
temp[k++]=arr[j++];
}
}
while(i<=mid){
temp[k++]=arr[i++];
}
while(j<=high){
temp[k++]=arr[j++];
}
for(int m=0;m<temp.length;m++){
arr[low+m]=temp[m];
}
ArrayUtils.printArray(arr);
}
}
class ArrayUtils{
public static void printArray(int[] arr){
for(int element:arr){
System.out.print(element+" ");
}
System.out.println();
}
public static void exchangeElements(int[] arr,int index1,int index2){
int temp;
temp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=temp;
}
}
/**
* <p>MethodName:main </p>
* <p>Description:常用排序算法之归并排序 </p>
* <p>@param args</p>
* <p>Return:void </p>
* @author Sunny
* @date 2016-9-27上午10:49:29
*/
public static void main(String[] args) {
int[] arr={7,6,4,9,0,5,2,8,3,1};
mergingSort(arr,0,9);
}
public static void mergingSort(int[] arr,int low,int high){
int mid=(low+high)/2;
if(low<high){
mergingSort(arr,low,mid);
mergingSort(arr,mid+1,high);
merge(arr,low,mid,high);
}
}
public static void merge(int[] arr,int low,int mid,int high){
int[] temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(arr[i]<arr[j]){
temp[k++]=arr[i++];
}else{
temp[k++]=arr[j++];
}
}
while(i<=mid){
temp[k++]=arr[i++];
}
while(j<=high){
temp[k++]=arr[j++];
}
for(int m=0;m<temp.length;m++){
arr[low+m]=temp[m];
}
ArrayUtils.printArray(arr);
}
}
class ArrayUtils{
public static void printArray(int[] arr){
for(int element:arr){
System.out.print(element+" ");
}
System.out.println();
}
public static void exchangeElements(int[] arr,int index1,int index2){
int temp;
temp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=temp;
}
}
分析:
分组为((((7 6) 4) (9 0)) (((5 2) 8) (3 1)))
结果展示:
6 7 4 9 0 5 2 8 3 1
4 6 7 9 0 5 2 8 3 1
4 6 7 0 9 5 2 8 3 1
0 4 6 7 9 5 2 8 3 1
0 4 6 7 9 2 5 8 3 1
0 4 6 7 9 2 5 8 3 1
0 4 6 7 9 2 5 8 1 3
0 4 6 7 9 1 2 3 5 8
0 1 2 3 4 5 6 7 8 9
4 6 7 9 0 5 2 8 3 1
4 6 7 0 9 5 2 8 3 1
0 4 6 7 9 5 2 8 3 1
0 4 6 7 9 2 5 8 3 1
0 4 6 7 9 2 5 8 3 1
0 4 6 7 9 2 5 8 1 3
0 4 6 7 9 1 2 3 5 8
0 1 2 3 4 5 6 7 8 9