|
public class Main {
private static int[] merge_sort(int[] array, int start, int end){
int[] result = new int[end-start+1];
if(start< end){
int mid= (start+end)/2;
int[] left= merge_sort(array, start, mid);
int[] right = merge_sort(array, mid+1, end);
result= merge(left,right);
} else if (start == end) {
result[0] = array[start];
return result;
}
return result;
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length+right.length];
int i=0;
int j=0;
int k=0;
while(i< left.length&&j< right.length){
if(left< right[j]){
result[k++] = left[i++];
}else{
result[k++] = right[j++];
}
}
while(i< left.length){
result[k++] = left[i++];
}
while (j< right.length) {
result[k++]= right[j++];
}
return result;
}
public static void main(String[] args) {
int[] arr = {2,1,4,6,3,182,21,12,213,412,2123,212,3,131,31};
int[] result = merge_sort(arr, 0, arr.length-1);
for (int i : result) {
System.out.print(i+" ");
}
}
}
运行:
C:\java>java Main
1 2 3 3 4 6 12 21 31 131 182 212 213 412 2123 |
|