首页 > 代码库 > 合并排序
合并排序
//过程示例
/*
[12]
[23]
---------------------
合并[12]and[23]得[12, 23]
---------------------
[21]
---------------------
合并[12, 23]and[21]得[12, 21, 23]
---------------------
[12]
[23]
---------------------
合并[12]and[23]得[12, 23]
---------------------
---------------------
合并[12, 21, 23]and[12, 23]得[12, 12, 21, 23, 23]
---------------------
[14]
[54]
---------------------
合并[14]and[54]得[14, 54]
---------------------
[64]
[43]
---------------------
合并[64]and[43]得[43, 64]
---------------------
---------------------
合并[14, 54]and[43, 64]得[14, 43, 54, 64]
---------------------
---------------------
合并[12, 12, 21, 23, 23]and[14, 43, 54, 64]得[12, 12, 14, 21, 23, 23, 43, 54, 64]
---------------------
[12, 12, 14, 21, 23, 23, 43, 54, 64]
*/
package com.example.sort;
import java.util.Arrays;
public class HebingSort {
public static void main(String[] args) {
int[] arr = new int[]{12,23,21,12,23,14,54,64,43};
System.out.println(Arrays.toString(fenChai(arr)));
}
//分拆
private static int[] fenChai(int[] arr) {
// TODO Auto-generated method stub
if(arr.length==1){
System.out.println(Arrays.toString(arr));
return arr;
}
int length1 = (int)Math.ceil((double)arr.length/2);//进1
int[] arr1 = new int[length1];
int[] arr2 = new int[arr.length-length1];
for(int i=0;i<arr.length;i++){
if(i<length1){
arr1[i] = arr[i];
}else{
arr2[i-length1] = arr[i];
}
}
int[] he1=fenChai(arr1);
int[] he2=fenChai(arr2);
return heBing(he1,he2);
}
//合并
private static int[] heBing(int[] arr1,int[] arr2) {
int arr[] = new int[arr1.length+arr2.length];
int indexOfArr1=0;
int indexOfArr2=0;
for(int i=0;i<arr.length;i++){
if(indexOfArr1==arr1.length){
arr[i] = arr2[indexOfArr2];
indexOfArr2++;
continue;
}
if(indexOfArr2==arr2.length){
arr[i] = arr1[indexOfArr1];
indexOfArr1++;
continue;
}
if(arr1[indexOfArr1]<arr2[indexOfArr2]){
arr[i] = arr1[indexOfArr1];
indexOfArr1++;
}else{
arr[i] = arr2[indexOfArr2];
indexOfArr2++;
}
}
System.out.println("---------------------");
System.out.println("合并"+Arrays.toString(arr1)+"and"+Arrays.toString(arr2)+"得"+Arrays.toString(arr));
System.out.println("---------------------");
return arr;
}
}
本文出自 “8967449” 博客,请务必保留此出处http://8977449.blog.51cto.com/8967449/1546010
合并排序