AcWing 787. 归并排序
原题链接
简单
作者:
爱做题的王旭旭
,
2020-10-13 20:58:08
,
所有人可见
,
阅读 2
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
int num = Integer.parseInt(bufferedReader.readLine());
int [] array = new int [num];
String [] result = bufferedReader.readLine().split(" ");
for (int i = 0;i<num;i++){
array[i] = Integer.parseInt(result[i]);
}
merge_sort(array,0,array.length-1);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
bufferedReader.close();
}
public static void merge_sort(int [] array , int left ,int right){
if (left>=right) return;
int middle = (left+right)/2;
merge_sort(array,left,middle);
merge_sort(array,middle+1,right);
merge(array,left,middle,middle+1,right);
}
public static void merge(int [] array ,int leftStart ,int leftEnd , int rightStart , int rightEnd) {
int i = leftStart;
int j = rightStart;
int k = 0;
int[] tmp = new int[rightEnd - leftStart + 1];
while (i <= leftEnd && j <= rightEnd) {
if (array[i] > array[j]) {
tmp[k++] = array[j++];
} else {
tmp[k++] = array[i++];
}
}
while (i <= leftEnd) {
tmp[k++] = array[i++];
}
while (j <= rightEnd) {
tmp[k++] = array[j++];
}
k = leftStart;
for(int element : tmp){
array[k++] = element;
}
}
}