1

所以在过去的几天里,我一直在试图弄清楚这段代码,但我一无所获。这是我得到的最远的,但现在它没有显示最终的排序数组,并且我尝试添加到返回合并语句之后的任何代码显然无法访问:/

import java.util.*;

public class MergeTestStringArray
{


  public static void main(String[] args)
  {
    ArrayList< String > array = new ArrayList< String >();

    array.add("John");
    array.add("Victor");
    array.add("Joe");
    array.add("Jackson");
    array.add("Anthony");
    array.add("Angelina");
    array.add("George");
    array.add("Paul");

    ArrayList< String > sortedArray = new ArrayList< String >();

    sortedArray = mergeSort(array);

    for (int i = 0; i < sortedArray.size(); i++)
    {
        System.out.println(" " + sortedArray.get(i) );
    }
  }

  public static ArrayList< String > mergeSort(ArrayList< String > list)
  {
    ArrayList < String > sorted = new ArrayList< String >();
    if (list.size() == 1)
    {
        sorted = list;
    } else {
        int mid1 = list.size() /2;

        ArrayList< String > left = new ArrayList< String >();
        ArrayList< String > right = new ArrayList< String >();

        for ( int x = 0; x < mid1; x++) {
            left.add(list.get(x));

        }
        for ( int x = mid1; x < list.size(); x++) {
            right.add(list.get(x));
        }

        System.out.println("Left Array: " + left);
        System.out.println("Right Array)" + right);

        mergeSort(left);
        mergeSort(right);
        mergeArray(left,right);
    }

    return sorted;
  }

private static ArrayList< String > mergeArray(ArrayList< String > left, ArrayList< String > right)
{
    ArrayList< String > merged = new ArrayList< String >();

    int i = 0;
    int l = 0;
    int r = 0;

    while (l < left.size() && r < right.size())
           {
              if ((left.get(l)).compareTo(right.get(r)) < 0)
              {
                 merged.add(left.get(l));
                 l++;
              }
              else
              {
                 merged.add(right.get(r));
                 r++;
              }

              i++;
           }


           while (l < left.size())
           {
              merged.add(left.get(l));
              l++;
              i++;
           }

           // Append rest of the values in the right half, if any...
           while (r < right.size())
           {
              merged.add(right.get(r));
              r++;
                  i++;
           }

    return merged;


  }

}
4

3 回答 3

1

您的错误在您的 mergeSort 函数中。具体来说,在您的递归情况下,您实际上从未将排序结果保存到merged列表中。尝试更换

mergeArray(left,right);

sorted = mergeArray(left,right);
于 2012-09-11T02:22:20.847 回答
1

不确定您的问题是什么,但是返回语句后的语句通常无法访问。一旦函数到达 return 语句,它将存在该函数并在该 return 语句处返回值..

于 2012-09-11T02:15:58.467 回答
0

将返回值赋给mergeArrayto sorted

sorted = mergeArray(left,right);

并分配您的 mergeSort 调用的结果:

        left = mergeSort(left);
        right = mergeSort(right);

此外,当您不打算使用它时,您不需要创建一个空的 ArrayList 来声明一个变量。

以下内容就足够了:

ArrayList < String > sorted;
于 2012-09-11T02:29:07.967 回答