算法之数组合并查找中位数

import org.thymeleaf.util.ArrayUtils;

class results {
     
    public static void main(String[] args) {
     
        int[] start = {
     5, 45, 9, 1};
        int[] end = {
     54, 445, 8};
        int[] s =selectionSort(start) ;
        int[] ss =selectionSort(end) ;
        int[] both =addBytes(s,ss);
        int[] both1=selectionSort(both);
        
        for (int test : both1)
        System.out.println(test);



//        System.out.println(results.findMedianSortedArrays(start, end));

    }


    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
     
        int m = nums1.length;
        int n = nums2.length;
        int left = (m + n + 1) / 2;
        int right = (m + n + 2) / 2;
        return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
    }

    public static int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
     
        if (i >= nums1.length) return nums2[j + k - 1];
        if (j >= nums2.length) return nums1[i + k - 1];
        if (k == 1) {
     
            return Math.min(nums1[i], nums2[j]);
        }
        int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
        int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;
        if (midVal1 < midVal2) {
     
            return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
        } else {
     
            return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
        }
    }

    private static int[] selectionSort(int[] arr) {
     
        for (int i = 0; i < arr.length - 1; i++) {
     
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
     
                if (arr[minIndex] > arr[j]) {
     
                    minIndex = j;
                }
            }
            if (minIndex != i) {
     
                int temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }
        }


        return arr;
    }
    /**
     *
     * @param data1
     * @param data2
     * @return data1 与 data2拼接的结果
     */
    public static int[] addBytes(int[] data1, int[] data2) {
     
        int[] data3 = new int[data1.length + data2.length];
        System.arraycopy(data1, 0, data3, 0, data1.length);
        System.arraycopy(data2, 0, data3, data1.length, data2.length);
        return data3;

    }
}

你可能感兴趣的:(算法笔记,算法)