java合併兩個升序數組爲一個新的升序數組(不使用排序算法)

public static void main(String[] args) { int[] nums1 = {1, 3, 41, 56, 78, 89, 100, 299}; int[] nums2 = {0, 2, 30, 50, 80, 99, 111, 180, 999}; int[] total = new int[nums1.length + nums2.length]; //兩個數組對比,每次取一個最小的數,取完後排除掉該數(該數組下標+1),直到取完兩個數組的全部的數
        int indexForOne = 0, indexForTwo = 0; for(int i = 0; i < total.length; i ++) { if(indexForOne == nums1.length) { //若是第一個數組中的數已經取完了,那就直接從第二個取
                total[i] = nums2[indexForTwo]; indexForTwo ++; }else if(indexForTwo == nums2.length) { total[i] = nums1[indexForOne]; indexForOne ++; }else if(nums1[indexForOne] <= nums2[indexForTwo]) { total[i] = nums1[indexForOne]; indexForOne ++; }else { total[i] = nums2[indexForTwo]; indexForTwo ++; } System.out.print(total[i] + " "); } }
相關文章
相關標籤/搜索