使用Shellsort按人口(Java)对国家列表进行排序

时间:2014-11-29 23:43:42

标签: java sorting shellsort

在我的程序中,我有一个类Sorting,它输入一个名为CountryUnsortedFormat的文件,其中包含一个国家及其人口的随机列表。该类应该使用shellsort按人口对国家进行排序并在屏幕上显示。

这是我的代码:

package assignment3;
import java.io.PrintWriter;
import java.io.File;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Assignment3 {

public static void main(String[] args) throws Exception{
    //Array for handling list of countries
    String[] line = new String[238];
    //read list of countries into array
    readInArray(line);
    //unsort the array
    unSort(line);


}

 static void readInArray(String[] line) throws Exception{
     Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountrySortedFormat.txt"));

     //Read in countries from sorted file into an array
    int k=0;
    while (stdIn.hasNextLine()){    
        line[k]=stdIn.nextLine();   
        k++;
    }
 }

 static void unSort(String[] line) throws Exception{
    PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");
    //Pick a random int from 1 to 238 called where
    //Write where into Unsorted Country Format file
    //Make where null
    //Repeat until all 238 countries are written in random order
    int j = line.length-1;
    Random r = new Random();
    while (j > 0){
        int where = r.nextInt(j)+1;
        out.println(line[where]);
        line = pop(where, line);
        j--;
    }
    out.close();

 }

 static String[] pop(int index, String[] line){
     String[] newLine = new String[line.length-1];
     int offset = 0;
     for (int i = 0; i<line.length; i++){
         if(i == index){
             offset = 1;
             continue;
         }
         newLine[i - offset] = line[i];
     }
     return newLine;
 }

}

class Sorting {

public static void main(String[] args) throws Exception{

    //Array for handling list of countries
    String[] line = new String[238];

    readInArray(line);
    shellsort(line);

    System.out.println(Arrays.toString(line));

}

static void readInArray(String[] line) throws Exception{
    Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));

    //Read in countries from unsorted file into an array
    int k=0;
    while (stdIn.hasNextLine()){    
        line[k]=stdIn.nextLine();   
        k++;
    }
}

static void shellsort(String[] line){
    int j;
    for(int gap = line.length-1/2; gap > 0; gap /= 2){
        for(int i = gap; i < line.length-1; i++){
            String tmp = line[i];
            for (j = i; j >= gap && getPopulation(line, j-gap) > getPopulation(line, i); j -= gap){
                line[j] = line[j -gap];
            }
            line[j] = tmp;
        }
    }
}

static int getPopulation(String[] line, int index){
    String populationString = line[index].substring(50,65).trim().replaceAll(",","");
    int population = Integer.parseInt(populationString);
    return population;
}


}

我的课程单独工作,但当放在一起时,我的程序不会打印到屏幕上。它显示的是“BUILD SUCCESSFUL(总时间:0秒)”

我做错了什么?

1 个答案:

答案 0 :(得分:1)

这显然是一项家庭作业,而且进一步帮助你是错误的。我首先会将您的代码组织成更易读的格式。例如:

public class Country{
    private int population;
    public Country(String line){
       // parse and set population
    }
    public int getPopulation(){
       return population;
    }
}

然后实现排序

# Sort an array countires[0...n-1].
# Start with the largest gap and work down to a gap of 1 
int j;
for(int gap = countries.length/2; gap > 0; gap /= 2){
    # Do a gapped insertion sort for this gap size.
    # The first gap elements countries[0..gap-1] are already in gapped order
    # keep adding one more element until the entire array is gap sorted 
    for(int i = gap; i < line.length; i++){
        # add countries[i] to the elements that have been gap sorted
        # save countries[i] in temp and make a hole at position i
        int temp = countries[i].getPopulation();
        # shift earlier gap-sorted elements up until the correct location for countries[i] is found
        for (j = i; j >= gap && a[j - gap].getPopulation() > temp; j -= gap){
            countries[j] = countries[j - gap]
        }
        # put temp (the original countries[i]) in its correct location
        countries[j] = temp
    }
}

或多或少直接从Wikipedia撕掉了,你拥有的......

这看起来像是需要更好的调试的情况。在填充println时删除一些断点或一些line。 Netbeans没有机会打印任何东西,因为没有什么可以打印出来的。或者你可能只是弄乱你的解析。您的子字符串中存在硬编码值,并且可能会出现中断的情况。使用正则表达式或扫描程序可以解决这个问题,只需要不是一个邪恶的函数集群。我不知道你的输入是什么样的,所以我无法告诉你。但是,我知道你的排序是有效的,因为我复制并粘贴了一些随机值并自己运行:

class Sorting {

    public static void main(String[] args) throws Exception{

        int[] line = new int[]{97,95,66,91,33,91,73,63,67,84,40,34,85,43,73,8,45,14,86,23,74,22,50,33,4,75,12,28,44,43,20,69,95,28,8,44,5,21,50,53,83,53,93,4,62,45,24,57,41,30,32,21,44,76,42,85,35,36,20,96,95,35,5,49,21,43,29,97,69,15,40,15,82,73,24,30,53,50,73,2,86,25,35,50,83,15,66,80,36,22,46,34,89,18,15,59,99,85,12,65};

        int j;
        for(int gap = line.length/2; gap > 0; gap /= 2){
            for(int i = gap; i < line.length; i++){
                int population = line[i];
                for (j = i; j >= gap && line[j - gap] > population; j -= gap){
                    line[j] = line[j -gap];
                }
                line[j] = population;
            }
        }
        for (int l : line) {
            System.out.println(l);
        }
    }
}

缺少错误日志听起来像环境问题,或者可能归结为未分类文件的样子,这很可能是错误的,因为我试图回答你之前的问题删除

使用随机Int和未分类文件遍历数组

所以代码的难度在于你最终不会得到一个混乱的数组。相反,你可能会有重复。让我们使用4 lines = ["Argentina","Barbados","Canada","Dominica"]

的数组来完成此操作

迭代1. j = 4,让我们where = 2,因此out = "Canada"

迭代2. j = 3没有什么可以阻止 where = 2 再次out = "Canada, Canada"

为了正确地对阵列进行加扰,我建议弹出所选值以防止重复。鉴于您使用的是普通旧数组而不是ArrayList,您应该有一个pop函数(尽管我建议使用ArrayList):

// pop(2,["Argentina","Barbados","Canada","Dominica"]) == ["Argentina","Barbados","Dominica"]
function String[] pop(int index, String[] list){
     newList = new String[list.length - 1]
     int offset = 0;
     for(int i; i < list.length; i++){
         if(i == index){
             offset = 1; // Start skipping 
             continue;
         }
         newList[i - offset] = list[i];
     }
     return newList;
}

你的新unSort应该:

public static void unSort(String[] line) throws Exception{
    Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));
    PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");

    int j = line.length; // Opposed to hardcoding 238
    Random r = new Random(); // Let's put random out so we don't have to continuously initialize
    while (j > 0){
        int where = r.nextInt(j);
        out.println(line[where]);
        line = pop(where, line); // get rid of what we just printed
        j--;
    }
    out.close();
}

当然还有其他改组,例如:您可以在line上执行Fisher-Yates,然后将其打印出来。我不完全理解你直接要求的东西,但我想它是这样的:

public static void unSort(String[] line) throws Exception{
    Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));
    PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");

    int j = line.length; // Opposed to hardcoding 238
    Random r = new Random(); // Let's put random out so we don't have to continuously initialize
    while (j > 0){
        int where = r.nextInt(line.length);
        if(line[where] != null){
            out.println(line[where]);
            j--;
            line[where] = null;
        }
    }
    out.close();
}

这保证没有重复。然而,这具有O(n)的最佳情况运行时间和无限循环的最坏情况。