内部排序:归并排序
基本思想:将序列不断的平衡划分,直到最小粒度上(仅有一个元素),不断向上在划分间归并得到排序元素。
时间复杂度:O(nlogn) 解释每一层递归都执行n/2次比较(所有的两辆划分间),递归深度为logn
关于递归:
1、犯了一个错误:mid = (end + start) / 2 mid = (end - start) / 2 + start
2、继续划分的条件:start < end
3、需要保持一个n的辅助数组,将归并的中间数据copy到辅助数组中,因为在执行归并是两个归并段是不能变的,归并完成后在写回到array中上递归。
-
import java.io.BufferedReader;
-
import java.io.IOException;
-
import java.io.InputStreamReader;
-
-
public class Sorter {
-
-
-
public static void main(String[] args) {
-
-
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
-
int[] array;
-
int[] result;
-
try {
-
String[] nums = input.readLine().split("");
-
array = new int[nums.length];
-
result = new int[nums.length];
-
for (int i = 0; i < nums.length; i++) {
-
array[i] = Integer.parseInt(nums[i]);
-
}
-
merge(array, result, 0, nums.length - 1);
-
-
for (int elem : result) {
-
System.out.print(elem + "");
-
}
-
-
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
}
-
-
public static void merge(int[] array, int[] result, int start, int end) {
-
-
int mid = (end + start) / 2;
-
-
System.out.println(start + "" + mid + "" + end);
-
-
if (start < mid)
-
merge(array, result, start, mid);
-
-
if (mid + 1 < end)
-
merge(array, result, mid + 1, end);
-
-
int p1 = start, p2 = mid + 1, counter = start;
-
while (p1 <= mid && p2 <= end) {
-
if (array[p1] < array[p2]) {
-
result[counter] = array[p1++];
-
} else {
-
result[counter] = array[p2++];
-
}
-
-
counter++;
-
}
-
-
while (p1 <= mid) {
-
result[counter++] = array[p1++];
-
}
-
-
while (p2 <= end) {
-
result[counter++] = array[p2++];
-
}
-
-
for (int i = start; i <= end; i++) {
-
array[i] = result[i];
-
}
-
}
-
}