简体   繁体   English

如何在 Java 中用比较器实现选择排序

[英]How to implement selection sort with a comparator in Java

I am developing a program to perform selection sort on a list of strings.我正在开发一个程序来对字符串列表执行选择排序。 The input for the program is 6 strings.该程序的输入是 6 个字符串。 The output for the program should be the list of strings sorted by their last character.该程序的 output 应该是按最后一个字符排序的字符串列表。

Here is what I have tried这是我试过的

import java.util.Arrays;
import java.util.Scanner;
import java.util.List;
import java.util.Comparator;

public class Exercise_20_21 {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 6 strings: ");
        // Step 1: proccess strings from input
        String data = input.next();
        String[] list = data.split(" ");
        for(int i=0; i < list.length; i++){
            System.out.print(list[i]+" ");
        }
        selectionSort(list, new Comparator<String>(){
            @Override
            public int compare(String w1, String w2){
                if(w1.charAt(0) > w2.charAt(0)){
                    return -1;
                }
                else if( w1.charAt(0) < w2.charAt(0)){
                    return 1;
                }
                else {
                    return 0;
                }
            }
        });
        for(int i=0; i < list.length; i++){
            System.out.print(list[i]+" ");
        }
    }

    

    public static <E> void selectionSort(E[] list, Comparator<? super E> comparator) {
        Arrays.sort(list,comparator);
    }
}

Expected:预期的:

Enter 5 strings: red blue green yellow orange pink
red blue orange pink green yellow

Actual:实际的:

Enter 6 strings: red blue green yellow orange pink
red red

How can I start on debugging this code?我怎样才能开始调试这段代码?

The problem with your code is not with the comparator itself.您的代码的问题不在于比较器本身。 You would want to use input.nextLine() for being able to read an entire line.您可能希望使用input.nextLine()来读取整行。 Using next will read only until the next delimiter (which is space in your case).使用next将只读到下一个定界符(在您的情况下为空格)。

For the comparator part, Java already provides a comparator for comparing strings and other objects.对于比较器部分,Java已经提供了比较器,用于比较字符串和其他对象。 This is Comparator.naturalOrder() and can be used as such:这是Comparator.naturalOrder()并且可以这样使用:

public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter 6 strings: ");
    // Step 1: proccess strings from input
    String data = input.nextLine();
    String[] list = data.split(" ");

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

    selectionSort(list, Comparator.naturalOrder());

    for (String s : list) {
        System.out.print(s + " ");
    }
}


public static <E> void selectionSort(E[] list, Comparator<? super E> comparator) {
    Arrays.sort(list, comparator);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM