Domanda

Im trying to sort a five names alphabetically as a test before moving to the command line and inputting a file. But im running into issues with it being alphabetical. my code is as follows:

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++;
                 }
            }
    }
}

and my output is:

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

where did I go wrong? How can I fix this?

È stato utile?

Soluzione

You have a bug in the following line.

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

The index into the array right should be i2 not i1.

        if (i2 >= right.length || (i1 < left.length &&
                             left[i1].compareToIgnoreCase(right[i2])<0)) {
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top