集册 Java实例教程 合并两个已排序的列表(按升序排列)方法:

合并两个已排序的列表(按升序排列)方法:

欢马劈雪     最近更新时间:2020-01-02 10:19:05

444
合并两个已排序的列表(按升序排列)方法:-只保留两个指针并将指针沿着用于创建新列表的列表移动


//package com.nowjava;
/**from N o w J a v a . c o m**/

public class Main {

    /**

     * This function merges two already sorted lists (in ascending order)

     * Approach:

     *    - just keeps two pointers and moves pointer along for whichever

     * list is being used to create the new list

     * @param list1

     * @param list2

     * @return

     */

    public static Integer[] merge(Integer[] list1, Integer[] list2) {

        int ptr1 = 0;

        int ptr2 = 0;

        int i = 0;

        Integer[] combined = new Integer[list1.length + list2.length];

        /*System.out.println("Combining ->");

           System.out.print("list 1:"); printArray(list1);

           System.out.print("list 2:"); printArray(list2);*/

        while (ptr1 < list1.length || ptr2 < list2.length) {

            if (ptr1 >= list1.length) {

                combined[i] = list2[ptr2];

                ptr2++;

            } else if (ptr2 >= list2.length || list1[ptr1] < list2[ptr2]) {

                combined[i] = list1[ptr1];

                ptr1++;

            } else {

                combined[i] = list2[ptr2];

          
展开阅读全文