Sorting linked list

//would anyone know how to sort this, tried to put in a bubble sort but i got some many errors i deleted it
import uuInOut;
class studentlist
public static void main(String [] args)
final int LENGTH = 10; //the length of the list
//declare variables
String name, temp3, searchName;
int age, id, current;
boolean present = false;
//create new linked list
LinkedList list = new LinkedList();
//open data
uuTextFile data = new uuTextFile("data.txt");
data.OpenInputFile();
//add data from data file to the linked list
while (!data.EOF)
name = data.ReadString();//read name
age = data.ReadInt();//read age
id = data.ReadInt();//read id
//new instance of studentrecord to add to list
StudentRecord temp = new StudentRecord(name, age, id);
list.insert(0, temp);//add to list
//Print The whole list
for (int x = 0; x < list.length(); x ++)
StudentRecord temp2 = (StudentRecord)list.elementAt(x);
temp2.printdetails();
System.out.println("First in list: ");
StudentRecord First = (StudentRecord)list.getHead().getElement();
First.printdetails();//print the first entered in the list
System.out.println("Last in List: ");
int x = list.length() - 1;
StudentRecord Last = (StudentRecord)list.elementAt(x);
Last.printdetails();//print the last entered in the list
System.out.println("Please Enter Current Position: ");
current = uuInOut.ReadInt();
StudentRecord next = (StudentRecord) list.elementAt(current + 1);
next.printdetails();//prints the next position in the list
System.out.println("Please Enter Name: ");
temp3 = uuInOut.ReadString();//reads in a name to search for in the list
//loop to search through the list for the name entered
for (int j = 0; j < list.length(); j++){
StudentRecord temp4 = (StudentRecord)list.elementAt(j);
searchName = temp4.getname();
if (temp3.equals(searchName))
present = true;
System.out.println(present);
if (present == true)
System.out.println("Student Name Found");
else System.out.println("Not in list" );
}

You could scrap this implementation and use a Collection class, then use Collections.sort. Or you could have your implementation implement the List interface and use Collections.sort. But more than likely you are supposed to do this for homework, so in that case I would try to implement the bubble sort and fix it until you don't get any errors. There are other sort routines you could use, but they are all more complicated than the bubble sort, so you will likely get many errors doing that too.
Good luck
Lee

Similar Messages

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Sort Linked List...

    I need help sorting a linked list.
    So far, in my sort method I have...
    public LinkedList sort();
    LinkedList newList = new LinkedList();
    Node ref;
    Node temp = new Node(head.getempID(); head.getempLast(), head.getempFirst(); head.getempDept(), head.getempSalary());
    for(ref = head; ref != null; ref.getNext());
    if(ref.getempID() <= temp.getEmpID());
    temp = (ref.getempID(), ref.getempLast(), ref.getempFirst(), ref.getempDept(), ref.getempSalary());
    newList.insert(temp); //???????
    return newList();
    // As you can tell, each one of my node's consists of an employee's id number, last name, first name, department, and salary...I need to sort the linked list by the employee's ID number. I can not figure out how to swap nodes though. PLEASE HELP A KID OUT!!!

    I was worng, my last data structure lecture today(I hope).
          |       |     |       |     |       |     |       |         |       |
    head->| Node1 |---->| Node2 |---->| Node3 |---->| Node4 |---etc-->| NodeN |->null
          |       |     |       |     |       |     |       |         |       |
    Q: How do you swap node2 with node3?
    A: Think about it!  Look at a picture if thats what you need. Draw the lines of reference to figure it out.
      1. Where does node1.next need to point to, how about node2.next, or node3.next?
      3. How do you change these without losing a node, are you going to need a temp?
      4. What about special case(switching node1 and node2)?
    This is simple problem solving skills.  I assume you have built the list yourself,
    so you have the basic knowledge base needed.

  • Merging two linked lists of integers that are sorted

    hey guys,
    i need to write a method to merge two linked lists of integers that are sorted into ascending order. the results should be a third linked list that is the sorted combination of the original lists.
    can someone help me start this? Basically, the method will be taking in two sorted linked lists of integers and merge them into one big sorted linked list.
    Im just looking to get some algorithm ideas and maybe one or two lines of pseudocode to get me started.
    thanks

    i can't destroy the original lists so im gonna need
    to create a new sorted list. then since both of the
    lists im using are sorted, i'll just have to copy one
    of them into the new list i created. Then i will get
    an item from the unused list and search that node in
    the new copied list and insert in appropriate
    position using the two Nodes...example(prev and
    curr).That can work. I'd probably do it by initializing a new list and compare the first items in each of the original lists, inserting the smaller in my new list and advancing to the next element in the original list from which I took the item, repeating the process until I copied each item from both original lists. Don't forget to take into account that you will reach the end of one list before the other.

  • Comparable linked list sorting

    i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!

    You don't need to copy anything.
    List list = new LinkedList(); // or ArrayList
    // list.add stuff
    Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted.

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Sorting singly linked list with minimum time complexity

    Hi ...
    anyone could tell me how can i sort singly linked list with minimum time complexity .... ????
    Regards...

    By MergeSort or QuickSort O(n log n). But then you
    have to first extract the objects in the list,sort
    them, then rebuild the list. But it will still bealot
    faster than by keeping the list linked.Technically, I believe insertion sort is marginally
    faster for small n ( <20 or so).Woohoo! So for 20 out of the possible 2147483648 array
    sizes Insetion is faster!
    Unfortunately, checking for that case probably wastes
    all the time you get from using the faster sort...
    That would depend on the actual distribution off array sizes. So it's an engineering decision.
    Sylvia.

  • Sorting My Linked List

    Alright, here's the problem. I have my linked list, either imported from a text file or inputted by the user. Now, I need to sort it by the date and the time strings... Yet, every time I do I get an NullPointException. Can anyone help? Here's my code for the list:
    public class ListReferenceBased implements ListInterface{
         //references to the linked list items
         private Node head;
         private int numItems; //number of items that exist in list
         //Default Constructor
         //sets both items to null
         public ListReferenceBased(){
              numItems = 0;
              head = null;
         //if the numItems in the list is empty
         //returns true.
         public boolean isEmpty(){     
              return numItems == 0;
         // returns numItems, aka the size of the list
         public int size(){
              return numItems;
         //finds a node by setting a node to the 'head'
         // and loops through to the index 'resetting'
         // curr to the 'next' node.
         private Node find(int index){
              Node curr = head;
              for( int skip = 1; skip < index; skip++){
                   curr = curr.getNext();
              return curr;
         public Object get(int index)
              throws ListIndexOutOfBoundsException{
              //catches if list does not reach the index given
              //loops through the index
              if(index >= 1 && index <= numItems){
              //sets curr to the index through find()
              Node curr = find(index);
              //sets dataitem to the current node
              Object dataItem = curr.getItem();
              return dataItem;
              }else{
              throw new ListIndexOutOfBoundsException("The List index is out of bounds on get");
         public void add(int index, Object item)
              throws ListIndexOutOfBoundsException{
              //checks to make sure there are no nodes yet
              //if there are inserts them in the list
              //by moving
              if(index >=1&& index<= numItems+1){
                   if(index==1){
                        // if no list exists
                        //creates a new node and sets it to head
                        Node newNode = new Node(item, head);
                        head = newNode;
                   }else{
                             //inserts the node at the index
                             //by finding it first
                             Node prev = find(index-1);
                   //creates a new node by placing the Object item
                   //and the 'new prev' node into a node
                   //'deleting' the old 'bonds'
                   Node newNode = new Node(item, prev.getNext());
                   rev.setNext(newNode);
                        //increments number of items in list
                        numItems++;
              }else{     
                        throw new ListIndexOutOfBoundsException("List index out of bounds");
         public void remove(int index)
              throws ListIndexOutOfBoundsException{
              //catches the list if it doesn't exist
              //checks to make sure list exists
              if(index>=1&& index<= numItems){
                   //if only the head exists
                   //calls next node else moves
                   //the node away and moves the prev
                   //on up.
                   if(index==1){
                        head = head.getNext();
                   }else{
                        Node prev = find(index-1);
                        Node curr = prev.getNext();
                        prev.setNext(curr.getNext());
                   //decreases the number of items in list
                   numItems--;
              }else{
         throw new ListIndexOutOfBoundsException("List index out of bounds");
         //sets the numItem to null telling the list it
         //does not exist
         public void removeAll(){
              head = null;
              numItems=0;
              

    Yeah, unfortunately, I had to design my own linked list for my assignment (that's taken almost 40+ hours). So, now every alogrithm I've tried to write seems to give me a null pointer, for example this one
    public void sort(){
              //loop through all existing nodes
              for(Node curr = head; curr != null; curr = curr.getNext()){
                   //parse the string of the current node
                   //to a string value
                   Node current = curr.getNext();
                   Node next = current.getNext();
                   Node temp;
                   String thisline = current.getItem().toString();
                   System.out.println(thisline);
                   StringTokenizer parser = new StringTokenizer ( thisline, "\t" );
                   String thisdate = parser.nextToken();
                   String thistime = parser.nextToken();
                   String thisline2 = next.getItem().toString();
                   System.out.println(thisline2);
                   StringTokenizer parser2 = new StringTokenizer ( thisline2, "\t" );
                   String thisdate2 = parser.nextToken();
                   String thistime2 = parser.nextToken();
                   //compares the dates of next in list
                   if(thisdate.compareTo(thisdate2)==1){
                        next.setNext(current);
                        current.setNext(next.getNext());
                        printList();
                        //if dates equal, compare the times
                   //if equal move to new position
                        //delete old position
    }Pretty much I believe moving the positions is causing the problems after the first run around. Any suggestions?

  • Sorting a doubly linked list

    Hello people!
    I have problems with sorting a doubly linked list, I have kind of got stuck just looking at the code and don't really know what I'm doing anymore...
    public void sortList()
    int flag = 0;
    DoubleNode temp; //Doubly Linked List Node
    temp = firstNode;
    String tempData;
    while (flag != 1)
    flag = 1;
    String data = (String)temp.element;
    while (temp.next != null)
    int comp = data.compareTo((String)temp.next.element);
    if (comp > 0)
    tempData = (String)temp.element;
    temp.element = temp.next.element;
    data = (String)temp.element;
    temp.next.element = tempData;
    flag = 0;
    else
    temp = temp.next;
    data = (String)temp.element;
    I'm trying to take an easy way around the problem by not swaping nodes but just the data the nodes contain. I'm pretty new to this and my prof. has just gone insane giving us this hardcore assignment.
    is this code even close to be correct?
    is this a good way of tackling the problem?
    thanks a lot! / Dan

    Okay, without going into any great detail about possible issues with the algorithm or code, it's gonna first be necessary to know some more about the DoubleNode class. For example, does it have a next method? If it does, then right off the bat your code will have to be adjusted so that where you have written "temp.next" you actually call the next method (which, if it is parameterless, would be "temp.next()"). As you have it written now, "temp.next" is accessing the "next" attribute of your DoubleNode instance, and I don't think that's what you're intending.
    -dSn

  • Linked List for custom insertion sorting not listing

    Hello fellow humans! :3 this is an assignment; the little menu's options are the tasks it's supposed to perform. Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. Cases 3 and 4 are completely useless without the first two; I've included them because being quite new I'd rather not exclude anything important.
    class with main method follows:
    package batch2;
    import java.io.*;
    class e21
    public static void main (String []args) throws IOException, NumberFormatException
    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    FromKeyboard key = new FromKeyboard();
    int a, option = 0, lrg;
    MyList alist, blist, clist;
    char fin = 'v';
    boolean avac, bvac, cvac, bord;
    NodeLD nodeaux = null;
    alist = new MyList();
    blist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'B', unsorted");
      System.out.println("3. Sort list 'B'");
      System.out.println("4. Mix lists 'A' & 'B' into a new sorted list 'C'");
      System.out.println("9. Exit");
      option = key.enterInt();
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          a = key.enterInt();
          if (a != -1){
            alist.insertToList(a);
            System.out.println("Test 1");     
          while (a != -1){
               a = key.enterInt();
            if (a != -1){
              System.out.println("Test 1.1");
              nodeaux = new NodeLD();
              nodeaux.theData(a);
              alist.sortInserList(nodeaux);
              System.out.println("Test 2, a="+a+"");
         System.out.println("List 'A', sorted by insertion:");
          alist.seeList();
        break;               
      case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
             System.out.println("Enter the integers you wish to add to list 'B'");
             System.out.println("Enter '-1' to finish");
             a = 0;
             while (a != -1){
                if (a != -1){
                  a = key.enterInt();
                  clist.insertToList(a);
             System.out.println("Unsorted list:");
             clist.seeList();
        break;
      case 3:
            while (clist.front != null){
          if (clist.front != null){
             blist.sortInserList(clist.front);
             clist.front = clist.front.givePrevious();
          System.out.println("List 'B', sorted");
          blist.seeList();
        break;
      case 4:
            while (blist.front != null){
         if (blist.front != null){
          alist.sortInserList(blist.front);
          blist.front = blist.front.givePrevious();
         System.out.println("List 'C', combining 'A' & 'B', sorted");
         clist.seeList();
        break;
      case 9:
         System.out.println("Program ended");
        break;
      default:
         System.out.println("Invalid option");
        break;
    while (option != 9);
    }Custom list class follows:
    package batch2;
    class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
           System.out.println(""+g.dat+"");
           g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         System.out.println("Test A");
         while (g.dat > pointer.dat && pointer != null){
           if (pointer.giveNext()!= null){
            pointer = pointer.giveNext();
            tag = false;
            System.out.println("Test A.b");
           else if (pointer.giveNext() == null) {
            tag = true;
            System.out.println("Test A.c");
           break;
         prepointer = pointer.givePrevious();
         if (pointer == null || tag){
           insertToList(g.dat);
           System.out.println("Test B. Pointer == null or tag == true");
         if (prepointer != null && !tag){
           g.thePrevious(prepointer);
           prepointer.theNext(g);
           System.out.println("Test C. prepointer != null && !tag");
         if (pointer != null && !tag){
           g.theNext(pointer);
           pointer.thePrevious(g);          
           System.out.println("Test D. pointer !=null && !tag");
         System.out.println("Test E. Right before return");
         return g.dat;
    }And here comes the accompanying Node class:
    package batch2;
    class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    }And last but not least, the part of FromKeyboard I'm using for this exercise, just in case:
    package batch2;
    import java.io.*;
    public class FromKeyboard
    public BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    public int enterInt(){
         System.out.flush();
         int integ = -1;
         try{
              integ = Integer.valueOf(input.readLine());
         catch(NumberFormatException e){
              System.err.println("Error: "+e.getMessage()+"");
         catch(IOException t){
              System.err.println("Error: "+t.getMessage()+"");
         return integ;
    }All help with regards as to why my lists aren't working and general comments/nudges on the sorting are welcome and appreciated.

    Hi Kevin, thank you for replying! I'll trim my code in a moment; as for a specific inquiry:
    >Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. >
    More direct approach to asking for help: These classes compile correctly and run, although the result is not what I'm aiming for: I get a single-noded list instead of the full list. Why isn't it keeping all the nodes but the last one only?
    Edited by: SquaredCircle on 09-Sep-2010 16:46
    That was fun :D this is my SSCCE for the main class:
    class e21SSCCE
    public static void main (String []args) throws NumberFormatException
    int a[] = {14, 25, 11, 43, 33, -1}, key[] = {1,2,9}, option = 0, i = 0, e = 0;
    MyList alist, clist;
    char fin = 'v';
    NodeLD nodeaux = null;
    alist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'C', unsorted");
    System.out.println("9. Exit");
      option = key[e];
      e++;
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          i = 0;
          if (a[i] != -1){
            alist.insertToList(a);
         i++;
         while (a[i] != -1){
    if (a[i] != -1){
         nodeaux = new NodeLD();
         nodeaux.theData(a[i]);
         alist.sortInserList(nodeaux);
         i++;
         System.out.println("List 'A', sorted by insertion:");
         alist.seeList();
    break;               
    case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
    System.out.println("Enter the integers you wish to add to list 'B'");
    System.out.println("Enter '-1' to finish");
    i = 0;
    while (a[i] != -1){
    if (a[i] != -1){
    clist.insertToList(a[i]);
                        i++;     
    System.out.println("Unsorted list:");
    clist.seeList();
    break;
    case 9:
         System.out.println("Program ended");
    break;
    default:
         System.out.println("Invalid option");
    break;
    while (option != 9);
    The cleaner version of the list class:class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
              System.out.println(""+g.dat+"");
              g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         while (g.dat > pointer.dat && pointer != null){
              if (pointer.giveNext()!= null){
                   pointer = pointer.giveNext();
                   tag = false;
              else if (pointer.giveNext() == null) {
                   tag = true;
                   break;
              prepointer = pointer.givePrevious();
              if (pointer == null || tag){
                   insertToList(g.dat);
              if (prepointer != null && !tag){
                   g.thePrevious(prepointer);
                   prepointer.theNext(g);
              if (pointer != null && !tag){
                   g.theNext(pointer);
                   pointer.thePrevious(g);          
         return g.dat;
    And the node class:class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    I followed the SSCCE guideline, and tried my best with it. The indentation checker was a broken link, though :c.
    Edited by: SquaredCircle on 09-Sep-2010 17:12                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Bubble Sort in Linked List

    so, everything works through the first iteration (don't know if this is an appropriate term for linked lists, but we just learned arrays) but then it stops. I thought that telling it to continue until position.next != null and increasing the position after every iteration would work but I think I have coded something incorrectly / am not taking something into consideration. I would be greatly obliged if you can offer any advice!
    Thanks,
    Hunter
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
                        previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
                                  previous = a;
                                  a = temp;
                    else
                                  a = a.next;
                      current = current.next;
                                  previous = previous.next;
                 position = position.next;
             head = head.next;

    First, thanks for the response! I have been trying println statements and really don't understand the problem. I have also gone through line-by-line and drawn out what I think is supposed to happen and still can't seem to fully figure out what I am doing wrong. Here is the full code, this might help with the 'definition of my list'.
        public class LinkedList
          public Node head;
           public LinkedList(int length)
             head = null;
             for (int i = 0; i < length; i ++)
                insert(i);
           public LinkedList()
             head = null;
           public void clear()
             head = null;
           public void insert(int n)
             Node current = new Node(n);
             current.next = head;
             head = current;
           public void insert(Node n, int index)
             Node previous, current;
             Node nnode = new Node(-10);
             nnode.next = head;
             previous = nnode;
             current = head;
             while (current != null && index > 0)
                current = current.next;
                previous = previous.next;
                index --;
             if (previous == nnode)
                n.next = head;
                head = n;
             else
                previous.next = n;
                n.next = current;
       //Delete the node at the zero-based index.
           public void delete(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 1; current --)
                currentnode = currentnode.next;
             if (currentnode == head)
                head = head.next;
             else
                currentnode.next = currentnode.next.next;
           public Node getNode(int index)
             Node nnode = new Node(-10);
             nnode.next = head;
             Node current = head;
             while(current.next != null && index > 0)
             {     current = current.next;
                index --;
             return current;
           public int getVal(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 0; current --)
                currentnode = currentnode.next;
          //currentnode should point to the node whose value we want.
             return currentnode.getVal();
           public void print()
             System.out.println();
             head.print();
           private void swap(Node pa, Node a, Node pb, Node b)
             Node temp = b.next;
             pa.next = b;
             if (a.next != b)
                b.next = a.next;
                pb.next = a;
             else
                b.next = a;
             a.next = temp;
           public void selectionSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next  != null)
                current = previous = position.next;
                a = position.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      current = a;
                      while(previous.next != current)
                         previous = previous.next;
                   a = a.next;
                if (current != previous)
                   Node t = position.next;
                   swap(position, t, previous, current);
             //System.out.println("****************");
             //head.print();
                position = position.next;
             head = head.next; //to lose the initial node.
          //System.out.println("end of sorting, head.print is");
          //head.print();
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
              previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
         previous = a;
         a = temp;
                    else
                    a = a.next;
                    current = current.next;
         previous = previous.next;
                 position = position.next;
             head = head.next;
          }

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

  • Linked List Insertion Sort

    Can anyone help me figure out the code for a linked list insertion sort by only manipulating the references? or provide me to a link that will.
    I can't seem to get it going.
    Thanks

    Well, first you have to split this topic up into its two pertinent portions:
    First, you have to know how to do an insertion sort. If you don't know how to do that, here's a good quick example:
    http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/InsertSort.html
    Next, you need to adapt this scheme to a linked list. The only real challenge here is knowing how to unlink an item in the list, relink it in the right place, and not disrupt the list. This is one of the first hits off google for the linked list:
    http://cslibrary.stanford.edu/103/

  • Sorting into Linked Lists

    What I want to do is make a Linked List that has options.
    1. Allows Duplicates & Non Sorted
    2. Allows Duplicates & Sorted Alphabetically
    3. Allows Duplicates & Sorted Reverse Alphabetically
    4. Doesn't Allow Duplicates & Non Sorted
    5. Doesn't Allow Duplicates & Sorted Alphabetically
    6. Doesn't Allow Duplicates & Sorted Reverse Alphabetically
    sortOrder and duplicate are my global variables controlling those two options.
    Reverse alphabetical and alphabetical will just be opposites.
    I've got the duplicates or non duplicates part working as well as non-sorted part.
        public void add(Object obj){
        // post: appends the specified element to the end of this list.
            Node temp = new Node(obj);
            Node current = head;
            Node hold = head;
            // starting at the head node, crawl to the end of the list
            //Takes care of duplicates
            if (!duplicate) {
                if (lookup(obj)) {
                return;
            System.out.println("OBJECT: " + obj.toString()); // See what I am passing
            if (sortOrder==0) { //non-sorted
                while(current.getNextNode() != null) {
                    current = current.getNextNode();
            // the last node's "next" reference set to our new node
                current.setNext(temp);
            if (sortOrder<0) { // decreasing
                while(current.getNextNode() != null) {
                    current = current.getNextNode();
                    System.out.println("CURRENT: " + current.getData().toString()); //Where I am sitting in the list
                    System.out.println("IF STATEMENT: "+ obj.toString().compareTo(current.getData().toString())); // Where the object sits alphabetically to current
                        if(obj.toString().compareTo(current.getData().toString())>0) {
                            hold.setNext(temp);
                            temp.setNext(current);
                            System.out.println("Object is closer to z Alphabetically");
                            return;
            // the last node's "next" reference set to our new node
    /*    if (sortOrder>0) { // increasing
            while(current.getNextNode() != null) {
                current = current.getNextNode();
                System.out.println("CURRENT: " + current.getData().toString());
                if (obj.toString().compareTo(current.getData().toString())<0){
        // the last node's "next" reference set to our new node
                    temp.setNext(current.getNextNode());
                    current.setNext(temp);
                    return;
    }

    humer015 wrote:
    What I want to do is make a Linked List that has options.
    1. Allows Duplicates & Non Sorted
    2. Allows Duplicates & Sorted Alphabetically
    3. Allows Duplicates & Sorted Reverse Alphabetically
    4. Doesn't Allow Duplicates & Non Sorted
    5. Doesn't Allow Duplicates & Sorted Alphabetically
    6. Doesn't Allow Duplicates & Sorted Reverse AlphabeticallyI'd set up 4 separate collections with the correct characteristics (6 if you think you need to keep the 'reverse order' versions separately). Remember, having 6 lists doesn't mean 6 sets of data; just 6 arrangements.
    sortOrder and duplicate are my global variables controlling those two options.Sounds like an implementation decision before its time to me, unless it's dictated by programs that you have no control over. Get your lists working and then decide how you want to implement your system parameters.
    HIH
    Winston

  • Doubly-linked List Sort has exited due to signal 10 (SIGBUS).

    What does this mean: "Doubly-linked List Sort has exited due to signal 10 (SIGBUS)."
    Thank you.

    Lady777 wrote:
    What does this mean: "Doubly-linked List Sort has exited due to signal 10 (SIGBUS)."
    SIGBUS is a bus error, meaning that your code is attempting to access an invalid address in memory. Most likely your linked list has a bad pointer in it that the code is trying to dereference. I'm not sure if a null pointer would cause a bus error but if your pointer contained garbage - due to not being properly initialized or due to being overwritten by bad data it certainly could.
    Steve

Maybe you are looking for

  • Copy any kind of file from content server to network directory

    Helli All The question: I nee to copy any kind of file from content server to any network directory. Explanation 1. transaction CV02N 2. There is attached file for a document in tab "Document data/Original" 3. This file stored in content server 4. I

  • Applet works on appletviewer but not browser

    Hi, I have just started using Java. I'm so new the only program I've tried to compile and run is "Hello World". I'm already having problems running the applet. I'm using Java 2 SDK on Windows 2000. The applet works just fine on appletviewer, but I ca

  • Significance of ResultSet.setFetchSize()

    We are using Oracle 8i as DB Server, WebLogic 6.1 as App Server and IIS 5.0 as Web Server on the different physical m/c. We are using OCI8 Driver. We have a utility that will act as a cache manager. We have to provide a query, it will hold the result

  • OBIEE 10.1.3.4.1 installations on AIX 6.1

    Hi Experts, Need your help, urgent need!!! I'm plannig to install OBIEE 10.1.3.4.1,BI Apps 7.9.6 ,Informatica,DAC, on AIX 6.1. Can you please help me installing OBIEE on AIX, If you have any screen shots that will be more helpful. Please help me in r

  • *Hi, I need to know Standard PM Reports and their Tcodes*

    I need to know Standard PM Reports and their Tcodes