使用Merge Sort(递归)按字母顺序对名称进行排序

时间:2014-04-08 00:15:29

标签: java mergesort alphabetical-sort

我试图在移动到命令行并输入文件之前按字母顺序将五个名称排序为测试。但我遇到的问题是按字母顺序排列。 我的代码如下:

import java.util.*;

public class MergeSortLines {
    public static void main(String[] args) {
        String[] list = {"Ryan", "Kelly", "Alex", "Kyle", "Riley"};
        System.out.println("before: " + Arrays.toString(list));
        mergeSort(list);
        System.out.println("after: " + Arrays.toString(list));
    }

    public static void mergeSort(String[] a) {
        if (a.length >= 2) {
            String[] left = new String[a.length / 2];
            String[] right = new String[a.length-a.length / 2];

            for (int i = 0; i < left.length; i++)
            {
                left[i] = a[i];
            }
            for (int i = 0; i < right.length; i++)
            {
                right[i] = a[i + a.length / 2];
            }

            mergeSort(left);
            mergeSort(right);

            merge(a, left, right);
        }
    }

    public static void merge(String[] result, String[] left, String[] right) {
        int i1 = 0;
        int i2 = 0;
        for (int i = 0; i < result.length; i++) {
            if (i2 >= right.length || (i1 < left.length &&
                                 left[i1].compareToIgnoreCase(right[i1])<0)) {
                      result[i] = left[i1];
                      i1++;
                 } else {
                      result[i] = right[i2];
                      i2++;
                 }
            }
    }
}

我的输出是:

 before: [Ryan, Kelly, Alex, Kyle, Riley]
 after: [Alex, Kyle, Riley, Kelly, Ryan]

我哪里出错了?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您在以下行中有错误。

        if (i2 >= right.length || (i1 < left.length &&
                             left[i1].compareToIgnoreCase(right[i1])<0)) {

数组right的索引应该是i2而不是i1

        if (i2 >= right.length || (i1 < left.length &&
                             left[i1].compareToIgnoreCase(right[i2])<0)) {