如何在java中不使用compare()方法进行选择排序?

如何在java中不使用compare()方法进行选择排序?,java,sorting,arraylist,Java,Sorting,Arraylist,欢迎来到我们的社区 我最近在学校开始学习java,其中一项任务是创建排序方法,如选择排序或插入排序,而不使用java自己的内置函数。我在网上查阅了很多,发现的所有方法都是针对数组的,而不是针对ArrayList的。作业的目标是按照尾巴长度对狗类进行排序,如果狗的尾巴长度相同,也要按照名称进行排序。 到目前为止,这就是我所做的 犬类 public class Dog { private static final double DEFAULT_TAIL_SIZE = 10.0; private st

欢迎来到我们的社区

我最近在学校开始学习java,其中一项任务是创建排序方法,如选择排序或插入排序,而不使用java自己的内置函数。我在网上查阅了很多,发现的所有方法都是针对数组的,而不是针对ArrayList的。作业的目标是按照尾巴长度对狗类进行排序,如果狗的尾巴长度相同,也要按照名称进行排序。 到目前为止,这就是我所做的

犬类

public class Dog {
private static final double DEFAULT_TAIL_SIZE = 10.0;
private static final double DEFAULT_TAX_SIZE = 3.7;
private static int count;
private String name;
private String breed;
private int age;
private int weight;
private double tailLenght;


public Dog(String name, String breed, int age, int weight) {
    //count++;
    this.name = name;
    this.age = age;
    this.breed = breed;
    this.weight = weight;
    this.tailLenght = tailLenght;

}

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

public String getBreed() {
    return breed;
}

public int getWeight() {
    return weight;
}

public void setAge(int age) {
    age = age <= 0 ? 1 : age;
}

public double getTailLength() {
    if (breed.equals("Tax") || breed.equals("dachshund")||breed.equals("tax") || breed.equals("Dachshund")) {
        return tailLenght = DEFAULT_TAX_SIZE;
    } else {
        return tailLenght = age * weight/DEFAULT_TAIL_SIZE;
    }

}
@Override
public String toString() {
    //System.out.println(String.format("name=%s breed=%s age=%d weight=%d taillenght=%.1f", name, breed, age, weight, getTailLength()));
    return name + " " + breed + " " + age + " " + weight + " " + getTailLength();
}
公共级狗{
私有静态最终双默认_TAIL_SIZE=10.0;
私人静态最终双默认_TAX_SIZE=3.7;
私有静态整数计数;
私有字符串名称;
私家犬;
私人互联网;
私有整数权重;
私人双尾长度;
公犬(犬串名称、犬串品种、整数年龄、整数体重){
//计数++;
this.name=名称;
这个。年龄=年龄;
这个品种;
重量=重量;
this.tailLenght=tailLenght;
}
公共字符串getName(){
返回名称;
}
公共整数getAge(){
回归年龄;
}
公共字符串getbride(){
回归品种;
}
公共整数getWeight(){
返回重量;
}
公共无效设置(整数){

age=age任务的要点是您应该自己实现
选择
插入
排序,而不是使用Java的内置排序功能。这就是您如何展示实现排序算法的一些知识

下面是一个选择排序的示例,它基于您的条件(tail和name),应该让您感觉到函数应该是什么样子。要做更多的练习,我建议您尝试自己实现插入排序

public class DogSorter {

    public void sort(ArrayList<Dog> dogs) {
        dogs.sort(new Comparator<Dog>() {
            @Override
            public int compare(Dog d1, Dog d2) {
                int comparison = 0;
                comparison = Double
                        .valueOf(d1.getTailLength())
                        .compareTo(d2.getTailLength());
                if (comparison == 0) {
                    comparison = String
                            .valueOf(d1.getName())
                            .compareTo(d2.getName());
                }
                return comparison;
            }
        });
    }

    public void selectionSort(ArrayList<Dog> dogs) {
        int n = dogs.size();

        // One by one move boundary of unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i + 1; j < n; j++) {
                Dog d1 = dogs.get(j);
                Dog d2 = dogs.get(min_idx);
                int comparison = Double
                        .valueOf(d1.getTailLength())
                        .compareTo(d2.getTailLength());
                if (comparison == 0) {
                    comparison = String
                            .valueOf(d1.getName())
                            .compareTo(d2.getName());
                }
                if (comparison < 0)
                    min_idx = j;
            }

            // Swap the found minimum element with the first
            // element

            // using built in swap
            // Collections.swap(dogs, min_idx, i);

            // using classic temp method
            Dog temp = dogs.get(min_idx);
            dogs.set(min_idx, dogs.get(i));
            dogs.set(i, temp);

            // using classic method without temp element
            // dogs.set(i, dogs.set(min_idx, dogs.get(i)));
        }
    }
}
公共级分拣机{
公共空白排序(ArrayList dogs){
dogs.sort(新比较器(){
@凌驾
公共整数比较(狗d1,狗d2){
整数比较=0;
比较=双
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
如果(比较==0){
比较=字符串
.valueOf(d1.getName())
.compareTo(d2.getName());
}
收益比较;
}
});
}
公共无效选择排序(ArrayList dogs){
int n=dogs.size();
//逐个移动未排序子阵列的边界
对于(int i=0;i

这里还有一个repl,您可以在实践中看到此函数:

是否有任何方法可以重新编写
集合.swap(dogs,min_idx,i);
最后?学校编译器对我们不使用已完成的java方法非常严格。我尝试创建自己的方法,但没有一个代码符合..
int temp=dogs.get(i);dogs.set(i,dogs.get(j));dogs.set(j,temp);
我将
int-temp
更改为
Dog-temp
,但随后我遇到编译问题,例如线程“main”java.lang.IndexOutOfBoundsException:索引12长度超出范围12您可以使用以下代码执行此操作:Dog-temp=dogs.get(min_idx);dogs.set(min_idx,dogs.get(i));dogs.set(i,temp);我还用一个示例更新了上面评论中的代码。这非常有用!!非常感谢:)
  import java.util.ArrayList;
import java.util.Random;

public class DogSorterRunner {
    private static final int NUMBER_OF_DOGS = 12;

private static final Random RND = new Random();
private static final String[] NAMES = { "Fido", "Karo", "Molly", "Bella", "Wilma", "Doris", "Sigge", "Charlie",
        "Ludde", "Bamse", "Lassie", "Ronja", "Ratata", "Maki", "Dora", "Luna", "Spike", "Mumsan", "Cherie" };

private static final String[] BREEDS = { "Labrador", "Golden retriever", "Tax", "Dachshund" };

private static String getRandomValueFromArray(String[] array) {
    return array[RND.nextInt(array.length)];
}

private static String randomName() {
    return getRandomValueFromArray(NAMES);
}

private static String randomBreed() {
    return getRandomValueFromArray(BREEDS);
}

private static int randomNumber() {
    return RND.nextInt(10) + 1;
}

public static void main(String[] args) {
    ArrayList<Dog> dogs = new ArrayList<>();

    for (int n = 0; n < NUMBER_OF_DOGS; n++) {
        Dog dog = new Dog(randomName(), randomBreed(), randomNumber(), randomNumber());
        dogs.add(dog);
    }

    new DogSorter().sort(dogs);

    for (Dog dog : dogs) {
        System.out.println(dog);
    }
}
public class DogSorter {

    public void sort(ArrayList<Dog> dogs) {
        dogs.sort(new Comparator<Dog>() {
            @Override
            public int compare(Dog d1, Dog d2) {
                int comparison = 0;
                comparison = Double
                        .valueOf(d1.getTailLength())
                        .compareTo(d2.getTailLength());
                if (comparison == 0) {
                    comparison = String
                            .valueOf(d1.getName())
                            .compareTo(d2.getName());
                }
                return comparison;
            }
        });
    }

    public void selectionSort(ArrayList<Dog> dogs) {
        int n = dogs.size();

        // One by one move boundary of unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i + 1; j < n; j++) {
                Dog d1 = dogs.get(j);
                Dog d2 = dogs.get(min_idx);
                int comparison = Double
                        .valueOf(d1.getTailLength())
                        .compareTo(d2.getTailLength());
                if (comparison == 0) {
                    comparison = String
                            .valueOf(d1.getName())
                            .compareTo(d2.getName());
                }
                if (comparison < 0)
                    min_idx = j;
            }

            // Swap the found minimum element with the first
            // element

            // using built in swap
            // Collections.swap(dogs, min_idx, i);

            // using classic temp method
            Dog temp = dogs.get(min_idx);
            dogs.set(min_idx, dogs.get(i));
            dogs.set(i, temp);

            // using classic method without temp element
            // dogs.set(i, dogs.set(min_idx, dogs.get(i)));
        }
    }
}