package 排序;
public class 归并排序 {
public static void sort(int[]arr){
chaifen(arr,0,arr.length-1);
for (int i:arr){
System.out.println(i);
}
}
public static void chaifen(int[] arr, int start, int end) {
if (start >= end) {
return;
}
int mid = (start + end) / 2;
chaifen(arr, start, mid);
chaifen(arr, mid + 1, end);
merge(arr, start, mid, end);
}
public static void merge(int[] arr, int start, int mid, int end) {
int[] temp = new int[end - start + 1];
int p1 = start;
int p2 = mid + 1;
int index = 0;//temp索引
while (p1 <= mid && p2 <= end) {
if (arr[p1] < arr[p2]) {
temp[index++] = arr[p1++];
} else {
temp[index++] = arr[p2++];
}
}
if (p1 > mid) {
while (p2 <= end) {
temp[index++] = arr[p2++];
}
}
if (p2 > end) {
while (p1<=mid){
temp[index++]=arr[p1++];
}
}
for (int i=start;i<=end;i++){
arr[i]=temp[i-start];
}
}
public static void main(String[] args) {
int[]test=new int[]{2,4,3,8,5,3,5,2,1,9};
sort(test);
}
}
Java排序---归并排序
最新推荐文章于 2024-04-07 20:33:32 发布