0

In one of my programs I am having trouble merging the two different lists and put it into an array and sorted from least to greatest. One of the teacher assistants said I can hard code it in to make it easier or do it the better way, the hard way of doing it. I want to do it the better way so I can think/become better of coding in. The TAs said it was doable in one for loop. Been thinking and trying for about 5 hours now and give up. Any suggestions?

import java.util.Scanner;

public class Lab10Part1 {

    public static void main(String[] args) {
        int[] list1, list2;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter list1 size and contents: ");
        int len1 = input.nextInt();
        list1 = new int[len1];
        for(int i = 0; i < list1.length; i++) {
            list1[i] = input.nextInt();
        }

        System.out.print("Enter list2 size and contents: ");
        int len2 = input.nextInt();
        list2 = new int[len2];
        for(int i = 0; i < list2.length; i++) {
            list2[i] = input.nextInt();
        }

        input.close();

        System.out.print("List1 is ");
        for(int i = 0; i < list1.length; i++) {
            System.out.print(list1[i] + " ");
        }
        System.out.println();
        System.out.print("List2 is ");
        for(int i = 0; i < list2.length; i++) {
            System.out.print(list2[i] + " ");
        }

        System.out.println();
        System.out.print("The merged list is ");
        for(int i = 0; i < merge(list1, list2).length; i++) {
        System.out.print(merge(list1, list2)[i] + " ");
        }

    }

    public static int[] merge(int[] list1, int[] list2) {
        int[] merge = new int[list1.length + list2.length];
        int min = Math.min(list1.length, list2.length);

        for(int i = 0, j = 0, k = 0; i < merge.length; k++) {
            if (min <= list1.length || min <= list2.length) {
                if(list2[j] <= list1[i]) {
                    merge[k] = list2[j];
                    j++;
                }
                else {
                    merge[k] = list1[i];
                    i++;
                }
                min++;
            }


            else if(list2.length >= list1.length) {
                if(list1[i] <= list2[j]) {
                    merge[k] = list1[i];
                    i++;
                }
                else {
                    merge[k] = list2[j];
                    j++;
                }
            }


        }
        return merge;
    }

}
Bubletan
  • 3,833
  • 6
  • 25
  • 33
Slate
  • 15
  • 4
  • You should probably store the result of merge in a local variable. – Bubletan Mar 06 '18 at 02:19
  • So, my logic and syntax are correct? And all I need to do is put int[] merge; into a different int array variable? – Slate Mar 06 '18 at 02:23
  • I didn't really read the code within the method very deeply but at the call site you should do something like `int[] merge = merge(list1, list2)` instead of repeatedly calling the method. – Bubletan Mar 06 '18 at 02:30
  • Are list1 and list2 guaranteed to be sorted already? – Ian Mc Mar 06 '18 at 02:33
  • @IanMc No, the user can enter how big or how small they want and enter any numbers at random. – Slate Mar 06 '18 at 02:35
  • It is very easy to merge two sorted lists, and maintain the sort in one for loop. It is not possible to merge two unsorted lists into a sorted list with one for loop. I am not sure then what the TA is saying. – Ian Mc Mar 06 '18 at 02:51
  • @IanMc In the example output, the user input was already sorted. Sorry, I thought the sample output was already sorted to understand the execution of the program better. And then I assumed that it can be done from any number that the user input into the program in one loop. Still, how can I get two (already) sorted list into one big list? – Slate Mar 06 '18 at 03:00
  • You might find your answer here: https://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array – Bubletan Mar 06 '18 at 03:05

2 Answers2

0

I think that you can solve the problem by using the collections( just List).The method of Array to List is Arrays.asList(array).And then use add and sort method.You can refer to Java Collections api for more.Forgive me for my English is not good.

Nexttt
  • 1
  • 1
0

Here is a way to merge sorted lists, and maintain the order in one for loop:

public class MergeSort {

public static void main(String[] args) {
    int[] a1 = { 1, 5, 6 };
    int[] a2 = { 2, 4, 6, 9, 11 };
    int[] a3 = merge(a1,a2);
    for (int i = 0; i<a3.length; i++)
        System.out.printf("%d ", a3[i]);
    System.out.println();

}
public static int[] merge(int[] list1, int[] list2) {
    int[] merge = new int[list1.length + list2.length];
    int i = 0; // Array index for list1
    int j = 0; // Array index for list2
    for (int k = 0; k < merge.length; k++) {
        int v1 = (i < list1.length) ? list1[i] : Integer.MAX_VALUE;
        int v2 = (j < list2.length) ? list2[j] : Integer.MAX_VALUE;
        if (v1 < v2) {
            merge[k] = v1;
            i++;
        } else {
            merge[k] = v2;
            j++;
        }
    }
    return merge;
}

}

Which creates output:

1 2 4 5 6 6 9 11 

Alternative to ternary operator

//int v1 = (i < list1.length) ? list1[i] : Integer.MAX_VALUE;
int v1;
if (i < list1.length)
    v1 = list1[i];
else 
    v1 = Integer.MAX_VALUE;
Ian Mc
  • 5,656
  • 4
  • 18
  • 25
  • What does the "?" operator mean? – Slate Mar 06 '18 at 03:07
  • It is the ternary operator. It works like this. The expression before the ? is evaluated. If it is true, then v1 is assigned to what is immediately after the ?. If it is false, then v1 is assigned to what is after the : – Ian Mc Mar 06 '18 at 03:11
  • Ah, so it is better than writing an if statement when there is only a true or false outcome? – Slate Mar 06 '18 at 03:17
  • That is really cool. Thank you so much! I was having so much trouble with this code because arrays are really confusing for me. Especially 2D arrays. Do you have any tips to think the way you did to help make programming easier? Or maybe suggestions? I know keep practicing is key and have to go through a lot of trial and error but as a college student, I'm trying to invest into learning programming as much as I can. – Slate Mar 06 '18 at 03:24
  • You are welcome. Arrays are hard for everyone at first. Have you tried this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – Ian Mc Mar 06 '18 at 03:30
  • I have not but I'll take a look at it. Once again thank you so much. – Slate Mar 06 '18 at 03:35