java归并排序
package com.lmz;
public class OrderByMerging {
public static void main(String[] args) {
int arr[]= {8,4,5,7,1,3,6,2};
int arrys[]= {4 ,5 ,7 ,8,1 ,2, 3, 6};
int[] add=new int[8];
mergeSort(arr,0,7,add);
for(int i = 0 ; i < arrys.length ; i++) {
System.out.print(arr[i]+" ");
}
}
public static void mergeSort(int[] arr,int left,int right,int[] temp) {
int mid = (left + right) / 2;
if (left < right) {
mergeSort(arr , left , mid , temp);
mergeSort(arr , mid , right , temp);
merge(arr , left , mid , right , temp);
}
}
public static void merge(int[] arr , int left , int mid , int right , int[] temps) {
int i = left ;
int j = mid + 1 ;
int temp = 0 ;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temps[temp++] = arr[i++] ;
}else {
temps[temp++] = arr[j++] ;
}
}
while (i <= mid) {
temps[temp++] = arr[i++] ;
}
while (j <= right) {
temps[temp++] = arr[j++] ;
}
for (int x = 0 ; x <= right ; x++) {
arr[x] = temps[x];
}
}
}