Java中的字符串合并排序

时间:2018-10-26 21:31:04

标签: java arrays string mergesort

因此,我正在尝试为字符串创建合并排序代码。我得到了适用于int的代码,但是当我将其调整为字符串时,它给出了nullPointerException。 它给了我第51、34和32行的错误。我试图删除从文件中读取的部分,然后将其直接写入字符串,但效果不佳。我怎样才能解决这个问题?

import java.io.*;
import java.util.Scanner;

public class sort {
    public static void main(String [] args) throws Exception {
        File file = new File("C:\\Java\\Algorithm Assignment\\names.txt"); 
        Scanner sc = new Scanner(file); 
        int ctr = 0;
        while (sc.hasNextLine()) {
             ctr++;
             sc.nextLine();
}  

        String [] names = new String [ctr];
        Scanner s1 = new Scanner(file);

        for(int i = 0; i < names.length; i++) {
            names[i] = s1.nextLine();
        }
        int low = names.length - names.length;
        int high = names.length - 1;
        mergeSort(names, low, high);
    }
    public static void mergeSort (String[] list, int lowIndex, int highIndex) {
        if (lowIndex == highIndex)
                return;
        else {
                int midIndex = (lowIndex + highIndex) / 2;
                mergeSort(list, lowIndex, midIndex);
                mergeSort(list, midIndex + 1, highIndex);
                merge(list, lowIndex, midIndex, highIndex);
                printIt(list, 0, list.length-1);
        }
    }

    public static void merge(String[] list, int lowIndex, int midIndex, int highIndex) {
       String [] L = new String[midIndex - lowIndex + 2];
            for (int i = lowIndex; i <= midIndex; i++) {
                L[i - lowIndex] = list[i];
            }

        String[] R = new String[highIndex - midIndex + 1];
            for (int i = midIndex + 1; i <= highIndex; i++) {
                R[i - midIndex - 1] = list[i];
            }           
        int i = 0, j = 0;
        for (int k = lowIndex; k <= highIndex; k++) {
            if (L[i].compareTo(R[j]) == 0 || L[i].compareTo(R[j]) < 1 ) {
                    list[k] = L[i];
                    i++;
            }
            else {
                    list[k] = R[j];
                    j++;
            }
        }

    }
     public static void printIt(String [] list, int num1, int num2) {
         for(int i = num1; i < num2; i++) {
             System.out.print(list[i]);
             System.out.print(" ");
         }
         System.out.println(" ");
     }
}

0 个答案:

没有答案