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.

7
  • Do you need to implement the sorting logic ? Can you not use the existing java utilities to sort ? Commented Nov 10, 2018 at 15:22
  • @janardhansharma yeah i have to implement it myself. It gives me a better opportunity to earn the subect Commented Nov 10, 2018 at 15:24
  • Other examples Commented Nov 10, 2018 at 15:24
  • head is always null. You always go through if(head == null && max < current.salary) { Commented Nov 10, 2018 at 15:27
  • @HovercraftFullOfEels none of the "duplicates" answer my question. I am doing linked ist manually and these tools don't help Commented Nov 10, 2018 at 15:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.