首页 > 代码库 > 归并排序
归并排序
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); 里使用的归并排序
其实就是对数组递归拆分两个数组,或者更多,然后几个数组进行归并,然后依次添加到临时数组中, 临时数组最后也是有序的,然后再用临时数组来修改原数组.
归并排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。