-
归并排序
-
public class Sort {
/**
*归并排序(递归实现)
*/
void mergeSort(int []arr,int len){
if (len>1){
//数组中元素个数大于1时执行
//1.将数组分组
int half=len/2;
int arr1[]=new int[half];
int arr2[]=new int[len-half];
for (int i=0;i<half;i++){
arr1[i]=arr[i];
}
for (int i=0,j=len/2;j<len;i++,j++){
arr2[i]=arr[j];
}
//2.递归调用
mergeSort(arr1,arr1.length);
mergeSort(arr2,arr2.length);
//3.合并
merging(arr1,arr1.length,arr2,arr2.length,arr);
}
}
//合并方法
void merging(int[] arr1, int length1, int[] arr2, int length2,int arr[]) {
int i,j,k;
i=j=k=0;
while (i<length1 && j<length2){
if (arr1[i]<arr2[j]){
arr[k++]=arr1[i++];
}else {
arr[k++]=arr2[j++];
}
}
while (i<length1){
arr[k++]=arr1[i++];
}
while (j<length2){
arr[k++]=arr2[j++];
}
}
}
-
测试类
public class Test {
public static void main(String[] args) {
int[] arr=new int[]{5, 2, 6, 9, 3, 0, 1, 7, 4, 8};
Sort s=new Sort();
s.mergeSort(arr,arr.length);
for(int k=0;k<arr.length;k++){
System.out.print(arr[k]);
}
}
}