0

I'm trying to sort singly linked lists using bubble sort. When I run my code it sorts the int and double lists. 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 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 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;
        }
    }
}


}

2 Answers2

0

There is nothing wrong at all. Note that the String "7" is greater than "50". You're looking at them as if there were numbers, but they aren't.

Eddie Lopez
  • 1,101
  • 7
  • 15
0

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

Refer to this link for ASCII table