I have been trying to teach this myself, but I judt don't get it. I have 10 books with ISBN number, title, name of author. The linked list should display the books sorted by ISBN. I hope this collections.sort is correct:

import java.util*;

public class Sort
{
    public class Sort
    {
    List<integer> MYLIST new ArrayList<integer>();

    //add integers 0 through 9 to the list
    for (int count = 0; count < 10; count++)
    MYLIST.add(count);

    // display the list
    System.out.println(List Contents:");
    System.out.println(MYLIST);

    // sort in acending order
    Collections.sort(MYLIST);

    //display the list
    System.out.println("\Sorted List:");
    System.out.println(MYLIST);

  }
    }

The linked list is this:

class LinkedList1
{


    private class Node
    {
        String value;   
        Node next;      



        Node(String val, Node n)
        {
            value = val;
            next = n;
        } 



        Node(String val)
        {
           // Call the other (sister) constructor.
           this(val, null);            
        }
    }   

    private Node first;  // list head
    private Node last;   // last element in list

    /**
       Constructor.
    */

    public LinkedList1()
    {
        first = null;
        last = null;        
    }

    /**
       The isEmpty method checks to see 
         if the list is empty.
         @return true if list is empty, 
         false otherwise.
    */

    public boolean isEmpty()
    {        
        return first == null;       
    }



    public int size()
    {
       int count = 0;
       Node p = first;     
         while (p != null)
       {
           // There is an element at p
           count ++;
           p = p.next;
       }
       return count;
    }


    public void add(String e)
    {
      if (isEmpty()) 
      {
          first = new Node(e);
          last = first;
      }
      else
      {
          // Add to end of existing list
          last.next = new Node(e);
          last = last.next;
      }      
    }



    public void add(int index, String e)
    {
         if (index < 0  || index > size()) 
         {
             String message = String.valueOf(index);
             throw new IndexOutOfBoundsException(message);
         }

         // Index is at least 0
         if (index == 0)
         {
             // New element goes at beginning
             first = new Node(e, first);
             if (last == null)
                 last = first;
             return;
         }

         // Set a reference pred to point to the node that
         // will be the predecessor of the new node
         Node pred = first;        
         for (int k = 1; k <= index - 1; k++)        
         {
            pred = pred.next;           
         }

         // Splice in a node containing the new element
         pred.next = new Node(e, pred.next);  

         // Is there a new last element ?
         if (pred.next.next == null)
             last = pred.next;         
    }


    public String toString()
    {
      StringBuilder strBuilder = new StringBuilder();

      // Use p to walk down the linked list
      Node p = first;
      while (p != null)
      {
         strBuilder.append(p.value + "\n"); 
         p = p.next;
      }      
      return strBuilder.toString(); 
    }


    public String remove(int index)
    {
       if (index < 0 || index >= size())
       {  
           String message = String.valueOf(index);
           throw new IndexOutOfBoundsException(message);
       }

       String element;  // The element to return     
       if (index == 0)
       {
          // Removal of first item in the list
          element = first.value;    
          first = first.next;
          if (first == null)
              last = null;             
       }
       else
       {
          // To remove an element other than the first,
          // find the predecessor of the element to
          // be removed.
          Node pred = first;

          // Move pred forward index - 1 times
          for (int k = 1; k <= index -1; k++)
              pred = pred.next;

          // Store the value to return
          element = pred.next.value;

          // Route link around the node to be removed
          pred.next = pred.next.next;  

          // Check if pred is now last
          if (pred.next == null)
              last = pred;              
       }
       return element;        
    }  



    public boolean remove(String element)
    {
       if (isEmpty()) 
           return false;      

       if (element.equals(first.value))
       {
          // Removal of first item in the list
          first = first.next;
          if (first == null)
              last = null;       
          return true;
       }

      // Find the predecessor of the element to remove
      Node pred = first;
      while (pred.next != null && 
             !pred.next.value.equals(element))
      {
          pred = pred.next;
      }

      // pred.next == null OR pred.next.value is element
      if (pred.next == null)
          return false;

      // pred.next.value  is element
      pred.next = pred.next.next;    

      // Check if pred is now last
      if (pred.next == null)
          last = pred;

      return true;       
    }

    public static void main(String [] args)
    {
        LinkedList1 ll = new LinkedList1();
        ll.add("Book1, Mr. Y, 12345");
        ll.add("Book2, Mrs. X, 28439");
        ll.add("Book3, Mr.XY, 39482");
        ll.add("Book4, Mrs. ZYZ, 38372");
        ll.add("Book5, Mr. UY, 93827");
        System.out.println("The members of the list are:");
        System.out.print(ll);
    }
}

Is this correct? If so, how do I sort it when I have more than one item in the node? How does it know which one the ISBN is. Also, how does collection.sort get the content? As you can see, right now I tell it what the numbers are going to be. I have not figured out how it gets it itself.

I don't get it. Can someone please show me how to do this?

Edited 4 Years Ago by Torf

Does your code compile and execute without error? What does it print out when it executes? Post its output and Add some comments to the post saying what is wrong with the output.

If you get errors, copy and paste the full text of the error messages.

I haven't tried it yet, to be honest. I first want to get the collection.sort into place. Then I can start worrying about it. It's not even complete yet, and I don't know how to do it. That's frustrating enough for now.

Edited 4 Years Ago by Torf

What are you waiting for? There are over 200 lines of code. I recommend that you compile and test frequently. Do not wait until all the code has been typed in. Type in a little, compile and test. Type in some more, compile and test. If you wait too long before testing it can be very hard to have to find all the problems all at one time, Little by little is better.

Edited 4 Years Ago by NormR1

Comments
Excellent advice

Like I said, I want to know how to do the collections.sort. That is my question. Not if the linked list ir error free. I didn't mean to imply this when I said "Is this correct". I wanted to know if the collections.sort works and, if it does, how to meet the requirements I set.

Edited 4 Years Ago by Torf

Does the rest of the code work like it is supposed to?

What happens when you use the Collections sort method? What problems are you having with it?

If so, how do I sort it when I have more than one item in the node? How does it know which one the ISBN is. Also, how does collection.sort get the content? As you can see, right now I tell it what the numbers are going to be. I have not figured out how it gets it itself.

The Collection.sort is not even correct.

If so, how do I sort it when I have more than one item in the node? How does it know which one the ISBN is. Also, how does collection.sort get the content? As you can see, right now I tell it what the numbers are going to be. I have not figured out how it gets it itself.

This is what it is currently doing and what he needs to do. It has to be changed, but I don't knwo how.

The Collection.sort is not even correct.

Please post the full text of any error messages.

  1. Norm is giving you good advice. Real programmers test early and test often. Adding more code to 200 lines that are probably full of errors is just making your life hard.
  2. Collections.sort sorts objects that implement the List interface. Since your class doesn't implement it you can't use Collections.sort You can either implement that interface or write your own sort method.
  3. Sorting in general uses a Comparator class that implements a compare method that you supply. It compares two objects and returns a value showing which sorts first. In your case that would compare the ISBNs of the two books. It's all explained in the API documentation.

No, not really. Nobody seems to understand what I want. I simply need something that will sort it. The collection.sort, in its current from, adds the integers to the list itself. This is NOT what I want. The integers are already in the list and it needs to use those. So, the collection.sort is not correct because it dosen't do what I need it to do. I only posted the complete list so that one can see how it looks like and if it would even work for this list.

Ok, so this dosen't work. Alright. I would use insertion sort then. I can use the comperator there, right? But adding list interface would work too. That would be easier, I think.

Implementing the List interface might not be as easy as you think. It has a lot of methods you'd need to write code for,

No, not really

No not really what?

Nobody seems to understand what I want.

On the contrary, there are a number of people here who know the difference between what you are asking for and what the really need. The first thing you need is to get you existing code to create and display lists working. Without that you can't even begin to test any sort code.

The collection.sort, in its current from, adds the integers to the list itself.

I presume you mean Collections.sort ? Anyway, Collections.sort doesn't add integers to anything.

I know it dosent... But if you had looked at the code:

//add integers 0 through 9 to the list
for (int count = 0; count < 10; count++)
MYLIST.add(count);

I suppsoe you can just remove it, but I don't see how it gets the values from the list then, in order to sort them. Or is it sufficient to reference to the list by name, like "Collections.sort(MYLIST);" ?
So I guess I should settle with insertion sort to sort it?

Edited 4 Years Ago by Torf

You would get a better list for sorting if you added random numbers to MYLIST instead of a sequence of numbers from 0 to 9

Isn't my linked lsit in #1 crap anyway? I mean, all it needs to do it to display the input. I probably could delete half of the code. Too many things I don't need for this simple taks. A simple, short linked list that holds the input, then add insertion sort so it can sort the input it holds.

This article has been dead for over six months. Start a new discussion instead.