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 - Java Collection Framework

Java examples for Collection Framework:Array Sort

Description

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

Demo Code


//package com.java2s;

public class Main {
    /**/*w ww  .  j  a v  a2 s  .c o  m*/
     * 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];
                ptr2++;
            }
            i++;
        }

        /*System.out.println("\tCombined =>");
           System.out.print("combined:"); printArray(combined);*/
        return combined;
    }
}

Related Tutorials