【问题标题】:Insertion Sorting compareTo()插入排序 compareTo()
【发布时间】:2017-07-16 01:53:41
【问题描述】:

所以我有一个对象列表,我想根据对象的每个名称的特征(按字母顺序)进行排序。我们需要按字母顺序“大致”,所以我有我认为是插入排序算法的平庸实现。但是,我只能按字母顺序正确排序一项。我已经在这里待了好几个小时,似乎遇到了障碍。

public void sort(){
  int i=1;
  while(list[i]!=null) { //while there is an element in the array
    String one=list[i-1].getName(); //get the name of the "first object"
    String two=list[i].getName();  //get the name of the "second object"

    if(two.compareTo(one)==0){ // if equal move on 
      i++;
    }
    else if(two.compareTo(one)<0){// two is before one
      Contact temp =list[i-1];  //store this temporarily
      list[i-1]=list[i]; //swap them
      list[i]=temp; //put temp back where it belongs
      i++;  //check next elements
    }
    i++
  }
}

这里是什么是列表,在排序之前和之后...http://image.prntscr.com/image/698cf44309ee43c29532ebe71a4925fe.png

【问题讨论】:

  • 我真的难倒堆栈溢出社区吗:D O_o
  • 在某种程度上,我想你做到了。你在问题中留下了关键信息,让每个人都猜到了,而 Stack Overflow 社区的一些人猜错了。如果你认为这会阻碍社区,我无法阻止你。

标签: java sorting compareto insertion


【解决方案1】:

有很多方法可以实现插入排序。我将向您解释一种更简单的方法,您可以按照您的解释按名称对对象数组进行排序。 插入排序的关键属性是:

  1. 插入排序从数组的左端开始并前进到 对。

  2. 这种排序机制不会查看右边的元素, 而是专注于当前遇到的项目并向后拖动 该项目到它的正确位置。

让我们记住这些事情!

    /*
     * Performs Insertion sort on given array of contacts!!
     */
    public static Contact[] sortContacts(Contact[] contacts){
        int n = contacts.length;
        // Advance the pointer to right
        for(int i = 0; i < n; i++){
            /*
             * Compare current item with previous item.
             * If current item is not in it's correct position,
             * swap until it's dragged back to it's correct position.
             * (Ascending order!!) 
             */
            for(int j = i; j > 0; j--){
                if(less(contacts[j], contacts[j - 1])){
                    swap(contacts, j, j - 1);
                }else{
                    break;
                }
            }
        }

        return contacts;

    }

    private static boolean less(Contact a, Contact b){
        return a.getName().compareTo(b.getName()) < 0;
    }

    private static void swap(Contact[] contacts, int i, int j){
        Contact temp = contacts[i];
        contacts[i] = contacts[j];
        contacts[j] = temp;
    }

这三种方法方便你的排序!!

现在来测试一下,让我们创建一些联系人并对其进行排序!!

        Contact one = new Contact();
        one.setName("tony");
        one.setPhone("6666");
        one.setMail("kkk@lll.com");

        Contact two = new Contact();
        two.setName("steve");
        two.setPhone("777");
        two.setMail("rrr@mmm.com");

        Contact three = new Contact();
        three.setName("clint");
        three.setPhone("333");
        three.setMail("ggg@sss.com");

        Contact four = new Contact();
        four.setName("bruce");
        four.setPhone("222");
        four.setMail("bbb@ccc.com");

让我们排序:

Contact[] res = Insertion.sortContacts(new Contact[]{one,two,three,four});
for(Contact c : res){
        System.out.println(c);
    }

这会产生输出:

Contact [name=bruce, mail=bbb@ccc.com, phone=222]
Contact [name=clint, mail=ggg@sss.com, phone=333]
Contact [name=steve, mail=rrr@mmm.com, phone=777]
Contact [name=tony, mail=kkk@lll.com, phone=6666]

这是根据每个联系人的姓名排序的!! 我希望这就是你想要实现的目标

【讨论】:

    【解决方案2】:

    首先,您必须了解插入排序的工作原理。

    • 您从未排序的一半列表中选择一个元素 (O(n))
    • 尝试将新选择的元素插入到排序的一半列表中(O(n))

    所以,插入排序是 O(n^2),这意味着它至少需要一个嵌套循环。

    这是修改后的版本:

        int i = 1;
        while(list[i] != null) {
            // i divides sorted and unsorted
            // try to insert i to the right place, so loop j from i-1 to 0
            int j = i;
            while (j > 0) {
                String one = list[j-1].getName();
                String two = list[j].getName();
                int cmp = one.compareTo(two);
                if (cmp <= 0) {
                    break;
                }
                Contact temp = list[j-1];
                list[j-1] = list[j];
                list[j] = temp;
                --j;
            }
            ++i;
        }
    

    【讨论】:

    • 我已经用你的例子运行了它。至少它对我有用。我按以下顺序获取联系人:Alex Bob Fred John steve
    • 嗯。那么你如何看待它们?我不明白它怎么不适合我
    • @PhilpAdoni 在您的示例中的前两个元素之后有一个Empty。我不知道这意味着什么,因为您没有向我们展示打印输出的方法。但如果这意味着list[2]null,那么您的原始代码看起来应该是数组的结尾。这与辛似乎做出的假设相同。如果数组中的 null 有其他含义,您需要让我们知道发生了什么。
    • @PhilpAdoni 请不要使用 .png 或其他图片来发布您的输出、您的程序或任何其他可以作为文本包含在您的问题中的内容。
    【解决方案3】:

    您可以在课堂上使用interface Comparable

    例子:

    public class Contact implements Comparable<Contact> 
    
        // ...
    
        public int compareTo(Contact other) {
           return getName().compareTo(other.getName());
        }
    }
    

    那么如果list是一个数组:

    Arrays.sort(list);
    

    【讨论】:

    • 谢谢,但我不熟悉这个,我们必须按照我最初尝试的方式来做,没什么特别的 :)
    • @PhilpAdoni 什么类型的列表?
    • 是联系人对象
    • 我的意思是,它是一个数组还是类似 ArrayList 的东西?
    • 这是一个数组!我们不能在这里使用列表
    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多