Home > OS >  Implementing Bubble Sort in the custom LinkedList. Sorting more than 4 elements triggers a NullPoint
Implementing Bubble Sort in the custom LinkedList. Sorting more than 4 elements triggers a NullPoint

Time:07-02

This code below is an implementation of linked List data structure.

I'm using Bubble sorting to sort its elements.

When I'm entering more than 4 elements, it throws a NullPointerException.

My code:

public class Main {
    
    Node head = null;
    Scanner sc = new Scanner(System.in);
    int number;
    
    void insert() {
        System.out.println("Enter the number of data. ");
        number = sc.nextInt();
        for (int i = 0; i < number; i  ) {
            System.out.println("Enter the data.");
            int data = sc.nextInt();
            Node n = new Node(data);
            if (head == null) {
                head = n;
            } else {
                n.next = head;
                head = n;
            }
        }
    }
    
    void sorting() {
        Node temp = head;
        for (int i = 0; i < number - 2; i  ) {
            for (int k = 0; k < number - i - 2; k  ) {
                while (temp.data > temp.next.data) {
                    int data1 = temp.data;
                    temp.data = temp.next.data;
                    temp.next.data = data1;
                    System.out.println(2);
                }
                System.out.println(1);
                temp = temp.next;
            }
        }
    }
    
    void print() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data   " ");
            temp = temp.next;
        }
    }
    
    class Node {
        int data;
        Node next;
        
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    
    public static void main(String[] args) {
        Main n = new Main();
        n.insert();
        n.sorting();
        n.print();
    }
}

How can I fix this?

CodePudding user response:

You can't just translate bubble-sort on array into a linked-list. The reason behind this is, that in the array, the inner-loop will reinitialize onto "0" for each iteration of the outer loop variable.

example -

for(int i=0; i<n-1; i  ) {
    for(int j=0; j<n-i-1; j  ){ }
}

Here inner-loop variable "j" will be reinitialized to 0 and start comparing values from it, each time the outer loop "i" increments.

But the same is not true, in your code. The temporary variable of head node, temp increments forever and never reinitialized to the start of the head again. In a simpler way, it swaps values only one time for each item.

To overcome this, you need to reinitialize your temp each time your outer loop iterates one.

Check this out.

CodePudding user response:

The main problem of your solution is a faulty implementation of sort() method.

You've declared variable temp in the wrong place (the code below). It should be reassigned with the reference to head-node at every step of the iteration of the outer for loop. But instead because of the line in the inner loop:

temp = temp.next;

variable temp at the end of the first iteration it points at the next node of the very last node in the list (which would be null, there's no next node that comes after the last node). And at the second step of iteration of the outer loop, temp.next produces a NullPointerException because temp is null. Hence, we should reinitialize it at the beginning of each iteration step.

You also don't need a while loop nested inside the inner for loop. The process of swapping the value of the list elements should happen inside the inner loop.

Sidenote: try to give your variables, as well as methods and classes meaningful names, for example size is more suitable than number.

Termination conditions < number - 2 in both for loops are incorrect. Instead, you need to iterate through the list until the node which is before the very last node (i.e. until the list size - 1) because you're checking the value of the next node inside the inner loop.

That's how your code can be fixed:

public class SinglyLinkedList {
    public static Scanner sc = new Scanner(System.in);
    
    private ConnectedComponents.SinglyLinkedList.Node head = null;
    private int size;
    
    public void insert() {
        System.out.println("Enter the number of Nodes to insert: ");
        
        int newNodes = sc.nextInt(); // don't override the size of the list
        size  = newNodes;            // add the number of new nodes to the current size
        
        for (int i = 0; i < newNodes; i  ) {
            System.out.println("Enter the data for the Node "   i   " :");
            int data = sc.nextInt();
            ConnectedComponents.SinglyLinkedList.Node newNode = new ConnectedComponents.SinglyLinkedList.Node(data);
            if (head != null) {
                newNode.next = head;
            }
            head = newNode;
        }
    }
    
    public void sorting() {
//            Node temp = head; <- that's a WRONG place to declare this variable, see variables in the loop
        
        if (size <= 1) return;    // there's no need to sort list of size 0 or 1, hence returning from the method
        
        
        for (int i = 0; i < size; i  ) {
            ConnectedComponents.SinglyLinkedList.Node cur = head;      // every iteration step of the outer loop should start with reassigning these variables
            
            for (int j = 0; j < size - 1 - i; j  ) {
                
                if (cur.data > cur.next.data) {
                    int temp = cur.data;
                    cur.data = cur.next.data;
                    cur.next.data = temp;
                }
                
                cur = cur.next;
            }
        }
    }
    
    void print() {
        ConnectedComponents.SinglyLinkedList.Node temp = head;
        while (temp != null) {
            System.out.print(temp.data   " ");
            temp = temp.next;
        }
    }
    
    public class Node {
        private int data;
        private ConnectedComponents.SinglyLinkedList.Node next;
        
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
}

Class Main:

public class Main {

    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList();
        list.insert();
        list.sorting();
        list.print();
    }
}
  • Related