简体   繁体   English

冒泡排序(单链表)错误

[英]bubble sort (singly linked list) error

I'm trying to sort singly linked lists using bubble sort. 我正在尝试使用冒泡排序对单链接列表进行排序。 When I run my code it sorts the int and double lists. 当我运行代码时,它将对int和double列表进行排序。 The weird thing is, when it sorts the String list it sorts all but one of the elements. 奇怪的是,当它对字符串列表进行排序时,它对除元素之一以外的所有元素进行了排序。 I have no idea why its happening. 我不知道为什么会这样。 Here's the output i'm getting. 这是我得到的输出。

2 46 39 43 35 50 7 38 45 32 2 46 39 43 35 50 7 38 45 32

2 7 32 35 38 39 43 45 46 50 2 7 32 35 38 39 43 45 46 50

2.0 7.0 32.0 35.0 38.0 39.0 43.0 45.0 46.0 50.0 2.0 7.0 32.0 35.0 38.0 39.0 43.0 45.0 46.0 50.0

2 32 35 38 39 43 45 46 50 7 2 32 35 38 39 43 45 46 50 7

import java.util.Random;

public class SLLBubbleSort{
public static void main(String[] args){
    Random rand = new Random();

    SLL<Integer> sll1 = new SLL<Integer>();
    SLL<Double> sll2 = new SLL<Double>();
    SLL<String> sll3 = new SLL<String>();
    for(int i=0;i<10;i++){
        int val = rand.nextInt(50)+1;
        sll1.addToHead(val);
        sll2.addToHead((double)val);
        sll3.addToHead(Integer.toString(val));
    }

    sll1.printAll();

    System.out.println("");
    BubbleSort(sll1);
    sll1.printAll();

    System.out.println("");
    BubbleSort(sll2);
    sll2.printAll();

    System.out.println("");
    BubbleSort(sll3);
    sll3.printAll();

}

public static <T extends Comparable<? super T>> void BubbleSort(SLL<T> list){
    for(int i=0;i<list.getLength();i++){
        SLLNode<T> current = list.head;
        SLLNode<T> next = current.next;

        for(int j=0;j<list.getLength()-1;j++){
            if(current.info.compareTo(next.info)>0){
                T temp = current.info;
                current.info = next.info;
                next.info = temp;
            }
            current = next;
            next = next.next;
        }
    }
}


}

There is nothing wrong at all. 完全没有错。 Note that the String "7" is greater than "50". 请注意, String “ 7”大于“ 50”。 You're looking at them as if there were numbers, but they aren't. 您正在看它们,好像有数字,但没有。

The result is perfectly fine, don't think them as number think them as string, as per the ascii value 0 comes first followed by 1, 2, 3 ...7, 8, 9, A, B, C ....X, Y, Z, a, b, c ... x, y, z 结果非常好,不要认为它们是数字,也不要认为它们是字符串,因为ascii值0首先出现,然后是1,2,3 ... 7,8,9,A,B,C ... .X,Y,Z,a,b,c ... x,y,z

Refer to this link for ASCII table 请参考此链接以获取ASCII表

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

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