bubble sort using linked list code example

Example 1: sort linked list using bubble sort

void linked_list::sort ()
{
  int i,j=0;
  int counter=0;
  node *curr=head;
  node *trail=head;
  node *temp=NULL;

  while (curr !=NULL)
  {
    curr=curr->next;    //couting the number of items I have in my list. 
    counter++;          //this works fine.
  }

  curr=head->next;          // reseting the curr value for the 2nd position.

  for (i=0; i<counter; i++)
  {
    while (curr != NULL)
    {
      if (trail->data > curr->data)
      {
        temp=curr->next;      //bubble sort for the pointers.
        curr->next=trail;
        trail->next=temp;

        temp=curr;         //reseting trail and curr. curr gets back to be infront.
        curr=trail;     
        trail=temp;

        if (j==0)   //i'm using j to determine the start of the loop so i won't loose the head pointer.
        {
          head=trail;
        }

      }
      j++;
      trail=curr;
      curr=curr->next;   //traversing thru the list. nested loop.
    }

    trail=head;
    curr=trail->next;
    curr->next=trail->next->next;  //traversing thru the list. outer loop.
    j=0;
  }
}

Example 2: bubble sort on a doubly linked list

public void sortList() {  
        Node current = null, index = null;  
        int temp;  
        //Check whether list is empty  
        if(head == null) {  
            return;  
        }  
        else {  
            //Current will point to head  
            for(current = head; current.next != null; current = current.next) {  
                //Index will point to node next to current  
                for(index = current.next; index != null; index = index.next) {  
                    //If current's data is greater than index's data, swap the data of current and index  
                    if(current.data > index.data) {  
                        temp = current.data;  
                        current.data = index.data;  
                        index.data = temp;  
                    }  
                }  
            }  
        }  
    }

Example 3: bubble sort linked list java

public static void main(String[] args){
  LinkedList linkedlist = new LinkedList()

Tags:

Java Example