快速排序之分割数组

xiaoxiao2021-02-28  123

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Permutation { public static void main(String[] args){ int nums[] = {12, 2, 3,9,1,15,4,20,10,-1}; boolean isUsed[] = new boolean[nums.length]; List<Integer> result = new ArrayList<Integer>(); List<List<Integer>> resultList = new ArrayList<List<Integer>>(); // doPermute(nums, isUsed, result, resultList); // System.out.println(resultList.toString()); Object[] aa = result.toArray(); // result.toArray(a) recMergeSort(nums, 0, nums.length-1); } public static void doPermute(int[] nums, boolean[] isUsed, List<Integer> result, List<List<Integer>> resultList){ if(result.size()==nums.length){ resultList.add(new ArrayList<>(result)); return; } for(int i = 0;i<nums.length;i++){ if(!isUsed[i]){ result.add(nums[i]); isUsed[i] = true; doPermute(nums, isUsed, result, resultList); result.remove(result.size()-1); isUsed[i] = false; } } } static int j =0; public static void recMergeSort(int[] arr, int low, int upper){ List<Integer> list = new ArrayList<Integer>(); for(int i =low;i<=upper;i++){ list.add(arr[i]); } // System.out.println("sub array: "+Arrays.asList(arr)); System.out.println("sub array: "+(j++)+" "+list); if(low == upper){ return; } else{ int mid = (low + upper)/2; recMergeSort(arr, low, mid); recMergeSort(arr, mid+1, upper); } } }

运行结果如下:

sub array: 0 [12, 2, 3, 9, 1, 15, 4, 20, 10, -1] sub array: 1 [12, 2, 3, 9, 1] sub array: 2 [12, 2, 3] sub array: 3 [12, 2] sub array: 4 [12] sub array: 5 [2] sub array: 6 [3] sub array: 7 [9, 1] sub array: 8 [9] sub array: 9 [1] sub array: 10 [15, 4, 20, 10, -1] sub array: 11 [15, 4, 20] sub array: 12 [15, 4] sub array: 13 [15] sub array: 14 [4] sub array: 15 [20] sub array: 16 [10, -1] sub array: 17 [10] sub array: 18 [-1]
转载请注明原文地址: https://www.6miu.com/read-18744.html

最新回复(0)