0

I have a linked list with 5 objects each with a salary as follows:

999, 999, 9009, 700, 9000

I need to manually (without any built-in ava function) sort the linked list based on these salaries and here is my implementation of the sort method:

public static void sortBySalary() {

    tmp = head;
    int i = linkLength();
    System.out.println(i);
    head = null;
    Employee maxSalary = new Employee();
    int max = 0;
    Employee current = tmp;

    for (int b = 0; b < i; b++) {
        current = tmp;
        max = 0;
        for (int c = 0; c < i; c++) {
            if(head == null && max < current.salary) {
                maxSalary = current;
                max = current.salary;
            }

            else if( max < current.salary && current.salary < head.salary) {

                    maxSalary = current;
                    max = current.salary;


            }

            System.out.println(current.salary);
            current = current.next;
        }

        maxSalary.next = null;
        insertFirst(maxSalary);

    }


}

The error I get is after the second iteration of the first loop, the list seems to point at null when it reaches salary 9009. it runs through 900 then 900 then 9009 then it points at null.

I am also open to different approaches.

khuew
  • 33
  • 4
  • Do you need to implement the sorting logic ? Can you not use the existing java utilities to sort ? – janardhan sharma Nov 10 '18 at 15:22
  • @janardhansharma yeah i have to implement it myself. It gives me a better opportunity to earn the subect – khuew Nov 10 '18 at 15:24
  • [Other examples](https://www.google.com/search?q=java+sorting+a+linked+list+site:stackoverflow.com) – Hovercraft Full Of Eels Nov 10 '18 at 15:24
  • `head` is always `null`. You always go through `if(head == null && max < current.salary) {` – isydmr Nov 10 '18 at 15:27
  • @HovercraftFullOfEels none of the "duplicates" answer my question. I am doing linked ist manually and these tools don't help – khuew Nov 10 '18 at 15:29
  • @isydmr at the start head is null then it is set through `insertFirst()` method. Double checked it with debugging mode on – khuew Nov 10 '18 at 15:30
  • @khuew: a key skill that you'll need to be a programmer is that of knowledge transfer, that being to learn from the general case and apply it to your own specific case. First you need to study the NPE link to learn how to debug these, then apply it to your specific situation. Then use it **will** answer your question. Luck. – Hovercraft Full Of Eels Nov 10 '18 at 15:32

0 Answers0