3 Replies Latest reply: Jan 8, 2007 6:48 AM by 807607 RSS

    Merge sorting arrays

    807607
      Hi!

      I'm trying to make a program that takes two already sorted arrays with people's last names in alphabetical order (String[] crLasts & String[] reLasts), and merge them into one array (String[] totalLasts)... using a non-recursive mergesort. Unfortunately, though, all that goes into the end array (totalLasts) is null values.

      Here's my code:

      int x1 = 0;
      int i = 0;
      int j = 0;

      while (x1 <= totalLasts.length-1)
      {
      if (i > crLasts.length-1)
      {
      totalLasts[x1] = reLasts[j];
      j++;
      }
      else if (j > reLasts.length-1)
      {
      totalLasts[x1] = crLasts;
      i++;
      }
      else if ((crLasts[i] != null) && (reLasts[j] != null))
      {
      if (crLasts[i].compareTo(reLasts[j]) < 0)
      {
      totalLasts[x1] = crLasts[i];
      i++;
      }
      }
      else if(reLasts[j].compareTo(crLasts[i]) < 0)
      {
      totalLasts[x1] = reLasts[j];
      j++;
      }
      else if(crLasts[i] == reLasts[j])
      {
      totalLasts[x1] = crLasts[i];
      i++;
      }

      x1++;
      }

      I greatly appreciate your help!

      Thanks,
      Anthony
        • 1. Re: Merge sorting arrays
          796365
          Start with 2 sorted arrays,

          read the first element from both arrays;

          compare elements;
          write out whichever one is lexically smaller (pick one if they're equal);
          read another entry from the same array whose element was written out;
          loop back to the compare above;

          You need to add EOF handling to this process. When either file shows EOF, there will still be one element that hasn't been written to the output.
          • 2. Re: Merge sorting arrays
            800329
            Shift one closing brace, and your code should work (unless either of the array's current value is null). The brace to be shifted is the one before the following line:
            else if (reLasts[j].compareTo(crLasts) < 0)
            and it should be put right before the line having
            x1++;
            And please use the code-tags for enclosing source to make it readable, if you post next time.
            • 3. Re: Merge sorting arrays
              807607
              OK Thanks! I really appreciate all the help, and next time I'll properly format the code if and when I post to this forum.

              Anthony