算法课程:输出int sort和方法对字符串进行排序

时间:2013-09-01 09:32:43

标签: java arrays sorting

我的作业要求我制作一个电视节目,我可以输入节目,删除,修改和排序。我坚持的是分拣部分。随着节目,它要求的名称,新的一集首映日和时间。这些是我需要按键排序的键。

程序提示用户输入其中一个键,然后程序需要排序(按日排序将按字母顺序排序)。

我创建了一个类并使用了一个数组。这是班级:

public class showInfo 
{
String name;
String day; 
int time;     
}

在代码中按时间排序的方法:

public static void intSort()
{
    int min;
    for (int i = 0; i < arr.length; i++) 
    {

        // Assume first element is min
        min = i;
        for (int j = i+1; j < arr.length; j++) 
        {
            if (arr[j].time < arr[min].time) 
            {
                min = j;
            }
        }

        if (min != i) 
        {
            int temp = arr[i].time;
            arr[i].time = arr[min].time;
            arr[min].time = temp;
        }
    }
    System.out.println("TV Shows by Time");
    for(int i = 0; i < arr.length; i++)
    {
        System.out.println(arr[i].name + " - " + arr[i].day + " - " + arr[i].time + " hours");
    }
}

当我调用它并将其输出到主屏幕时,它仅显示“按时间显示的电视节目”而不显示列表。为什么是这样?

另外,我需要制作一种方法,我可以使用它来对日期和名称(两个字符串)进行排序。如何在不使用方法中的那些特定数组(arr [i] .name,arr [i] .day)的情况下执行此操作?

任何帮助将不胜感激!提前谢谢!

3 个答案:

答案 0 :(得分:3)

在代码的这一部分

if (min != i) {
    int temp = arr[i].time;
    arr[i].time = arr[min].time;
    arr[min].time = temp;
}

您只是在改变移动整个对象的时间。要修复它,代码必须像这样:

if (min != i) {
    //saving the object reference from arr[i] in a temp variable
    showInfo temp = arr[i];
    //swapping the elements
    arr[i] = arr[min];
    arr[min] = temp;
}

这将是最好使用̶Arrays#sort您提供自定义̶̶C̶o̶m̶p̶a̶r̶a̶t̶o̶r̶̶的阶级进行排序̶(如果允许以使用该方法)。短的例子:̶

showInfo[] showInfoArray = ...
//your array declared and filled with data
//sorting the array
Arrays.sort(showInfoArray, new Comparator<showInfo>() {
    @Override
    public int compare(showInfo showInfo1, showInfo showInfo2) {
        //write the comparison logic
        //basic implementation
        if (showInfo1.getTime() == showInfo2.getTime()) {
             return showInfo1.getName().compareTo(showInfo2.getName());
        }
        return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
    }
});
//showInfoArray will be sorted...

由于您必须使用自定义排序算法并支持不同的方式对数据进行排序,因此您只需更改比较数据的方式即可。这意味着,在您当前的代码中,更改此部分

if (arr[j].time < arr[min].time) {
    min = j;
}

更像通用的东西,如

if (compare(arr[j], arr[min]) < 0) {
    min = j;
}

您只需要根据需要更改compare方法的实现。但是,创建和维护一种可以支持不同方式来比较数据的方法太复杂了。所以最好的选择似乎是Comparator<showInfo>,使你的代码看起来像这样:

if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
    min = j;
}

其中showInfoComparator包含比较元素的逻辑。现在,您的intSort会变得更通用:

public static void genericSort(Comparator<showInfo> showInfoComparator) {
    //your current implementation with few modifications
    //...
    //using the comparator to find the minimum element
    if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
        min = j;
    }
    //...
    //swapping the elements directly in the array instead of swapping part of the data
    if (min != i) {
        int temp = arr[i].time;
        arr[i].time = arr[min].time;
        arr[min].time = temp;
    }
    //...
}

现在,您只需编写一组支持自定义条件的Comparator<showInfo>实现。例如,这里使用showInfo字段比较time个实例:

public class ShowInfoTimeComparator implements Comparator<showInfo> {
    @Override
    public int compare(showInfo showInfo1, showInfo showInfo2) {
        //write the comparison logic
        return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
    }
}

另一个使用name字段的比较器:

public class ShowInfoNameComparator implements Comparator<showInfo> {
    @Override
    public int compare(showInfo showInfo1, showInfo showInfo2) {
        //write the comparison logic
        return showInfo1.getName().compareTo(showInfo2.getName());
    }
}

现在在您的代码中,您可以像 1

一样调用它
if (*compare by time*) {
    genericSort(showInfoArray, new ShowInfoTimeComparator());
}
if (*compare by name*) {
    genericSort(showInfoArray, new ShowInfoNameComparator());
}
if (*another custom rule*) {
    genericSort(showInfoArray, new ShowInfoAnotherCustomRuleComparator());
}

现在,您可以使用两个或多个字段来实现自定义规则,例如比较showInfo个对象。以您的nameday字段为例(如问题中所述):

public class ShowInfoNameAndDayComparator implements Comparator<showInfo> {
    @Override
    public int compare(showInfo showInfo1, showInfo showInfo2) {
        //write the comparison logic
        int nameComparisonResult = showInfo1.getName().compareTo(showInfo2.getName());
        if (nameComparisonResult == 0) {
            return showInfo1.getDay().compareTo(showInfo2.getDay());
        }
        return nameComparisonResult;
    }
}

1 :还有其他方法可以使用大量的if语句来解决这个问题,但看起来像是在问题范围之外。如果没有,请编辑问题并添加它以显示解决此问题的其他方法。


您当前代码的其他提示:

  • 使用CamelCase声明类的名称,其中类名的第一个字母为大写,因此必须将showInfo类重命名为ShowInfo
  • 要访问类的字段,请使用正确的getter和setter,而不是将字段标记为public或保留default范围。这意味着,您的ShowInfo课程应该成为:

    public class ShowInfo {
        private String name;
        private String day; 
        private int time;
        public String getName() {
            return this.name;
        }
        public void setName(String name) {
            this.name = name;
        }
        //similar for other fields in the class
    }
    

答案 1 :(得分:1)

为什么不使用Collection来做这种事情。此外,在您添加的示例中,您只是更改给定对象的一个​​属性,同时排序,尽管您没有在给定列表中更改整个对象的位置。

创建一个List,其中包含所有Shows的引用,现在将Show中的一个List的每个属性与List进行比较。一旦算法感觉到,需要进行交换,只需从temp中选择引用,将其保存在reference变量中,将其替换为此位置的新temp,并将副本设置为存储在List变量中的副本。您已完成,import java.io.*; import java.util.*; public class Sorter { private BufferedReader input; private List<ShowInfo> showList; public Sorter() { showList = new ArrayList<ShowInfo>(); input = new BufferedReader( new InputStreamReader((System.in))); } private void createList() throws IOException { for (int i = 0; i < 5; i++) { System.out.format("Enter Show Name :"); String name = input.readLine(); System.out.format("Enter Time of the Show : "); int time = Integer.parseInt(input.readLine()); ShowInfo show = new ShowInfo(name, time); showList.add(show); } } private void performTask() { try { createList(); } catch (Exception e) { e.printStackTrace(); } sortByTime(showList); } private void sortByTime(List<ShowInfo> showList) { int min; for (int i = 0; i < showList.size(); i++) { // Assume first element is min min = i; for (int j = i+1; j < showList.size(); j++) { if (showList.get(j).getTime() < showList.get(min).getTime()) { min = j; } } if (min != i) { ShowInfo temp = showList.get(i); showList.set(i, showList.get(min)); showList.set(min, temp); } } System.out.println("TV Shows by Time"); for(int i = 0; i < showList.size(); i++) { System.out.println(showList.get(i).getName() + " - " + showList.get(i).getTime()); } } public static void main(String[] args) { new Sorter().performTask(); } } class ShowInfo { private String name; int time; public ShowInfo(String n, int t) { name = n; time = t; } public String getName() { return name; } public int getTime() { return time; } } 已排序: - )

以下是一个小例子,求助:

By Name

编辑2:

对于排序private void sortByName(List<ShowInfo> showList) { int min; for (int i = 0; i < showList.size(); i++) { // Assume first element is min min = i; for (int j = i+1; j < showList.size(); j++) { int value = (showList.get(j).getName()).compareToIgnoreCase( showList.get(min).getName()); if (value < 0) min = j; } if (min != i) { ShowInfo temp = showList.get(i); showList.set(i, showList.get(min)); showList.set(min, temp); } } System.out.println("TV Shows by Time"); for(int i = 0; i < showList.size(); i++) { System.out.println(showList.get(i).getName() + " - " + showList.get(i).getTime()); } } ,您可以使用此功能:

Comparable<?>

编辑3:

在现有类中添加Enumeration接口,以根据指定的输入执行排序。虽然可以通过使用import java.io.*; import java.util.*; public class Sorter { private BufferedReader input; private List<ShowInfo> showList; private int command; public Sorter() { showList = new ArrayList<ShowInfo>(); input = new BufferedReader( new InputStreamReader((System.in))); command = -1; } private void createList() throws IOException { for (int i = 0; i < 5; i++) { System.out.format("Enter Show Name :"); String name = input.readLine(); System.out.format("Enter Time of the Show : "); int time = Integer.parseInt(input.readLine()); ShowInfo show = new ShowInfo(name, time); showList.add(show); } } private void performTask() { try { createList(); } catch (Exception e) { e.printStackTrace(); } System.out.format("How would you like to sort : %n"); System.out.format("Press 0 : By Name%n"); System.out.format("Press 1 : By Time%n"); try { command = Integer.parseInt(input.readLine()); } catch (Exception e) { e.printStackTrace(); } sortList(showList); } private void sortList(List<ShowInfo> showList) { int min; for (int i = 0; i < showList.size(); i++) { // Assume first element is min min = i; for (int j = i+1; j < showList.size(); j++) { showList.get(j).setValues(command); int value = showList.get(j).compareTo(showList.get(min)); if (value < 0) { min = j; } } if (min != i) { Collections.swap(showList, i, min); } } System.out.println("TV Shows by Time"); for(int i = 0; i < showList.size(); i++) { System.out.println(showList.get(i).getName() + " - " + showList.get(i).getTime()); } } public static void main(String[] args) { new Sorter().performTask(); } } class ShowInfo implements Comparable<ShowInfo> { private String name; private int time; private int command; public ShowInfo(String n, int t) { name = n; time = t; } public String getName() { return name; } public int getTime() { return time; } public void setValues(int cmd) { command = cmd; } public int compareTo(ShowInfo show) { int lastCmp = 1; if (command == 0) { lastCmp = name.compareTo(show.name); } else if (command == 1) { if (time < show.time) { lastCmp = -1; } else if (time == show.time) { lastCmp = 0; } else if (time > show.time) { lastCmp = 1; } } return lastCmp; } } 来改进逻辑,但是让OP尝试他/她的手: - )

{{1}}

答案 2 :(得分:1)

使用易于实现的选择排序算法

for (int i = 0; i < arr.length; i++)
        {
            for (int j = i + 1; j < arr.length; j++)
            {
                if (arr[i].time > arr[j].time) // Here ur code that which should be compare
                {
                    ShowInfo temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }

无需检查min元素。浏览此维基http://en.wikipedia.org/wiki/Selection_sort