归并排序
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Test { public static int[] sort(int[] nums, int low, int high) { //System.out.println(Arrays.toString(nums)); int mid = (low + high) / 2; System.out.println(low + " " + mid + " " + high); if (low < high) { // 左边 sort(nums, low, mid); // 右边 sort(nums, mid + 1, high); // 左右归并 System.out.println("beg merge --- " + low + " " + mid + " " + high); merge(nums, low, mid, high); System.out.println(Arrays.toString(nums)); } return nums; } public static void merge(int[] nums, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low; // 左指针 int j = mid + 1; // 右指针 int k = 0; // 临时数组指针 // 把较小的数先移到新数组中 // mid作为分界点比较 while (i <= mid && j <= high) { if (nums[i] < nums[j]) { temp[k++] = nums[i++]; } else { temp[k++] = nums[j++]; } } System.out.println("1" + Arrays.toString(temp)); // 把左边剩余的数移入数组 while (i <= mid) { temp[k++] = nums[i++]; } System.out.println("2 " + Arrays.toString(temp)); // 把右边边剩余的数移入数组 while (j <= high) { temp[k++] = nums[j++]; } System.out.println("3 " + Arrays.toString(temp)); // 把新数组中的数覆盖nums数组 for (int k2 = 0; k2 < temp.length; k2++) { nums[k2 + low] = temp[k2]; } } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {5, 4, 3, 2, 1};// 6, 9, 0, 5, 4 }; System.out.println(Arrays.toString(nums)); sort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); Integer[] a = new Integer[] { 3, 2, 32, 3 }; List<Integer> list = (List<Integer>) Arrays.asList(a); Collections.sort(list); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("test"); } }
Collections.sort(list); 里使用的归并排序
其实就是对数组递归拆分两个数组,或者更多,然后几个数组进行归并,然后依次添加到临时数组中, 临时数组最后也是有序的,然后再用临时数组来修改原数组.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。