bubble sort implementation on linked lists

后端 未结 6 1411
小蘑菇
小蘑菇 2020-12-11 14:06

I have to implement a BubbleSort algorithm on a Linked List instead of an array. I\'m new to java so I don\'t really know how to put it in code. But I gave it a try and here

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 14:26

    In your list it will help to have a size field, to store the number of elements in the list. Also make the class SinglyNode implement Comparable so the compareTo method behaves as you want. The in-place swapping of two elements in Single LinkedList is actually quite involved, and the performance is really bad!

    public void bubbleSort
    {
      for (int i = 0; i < size; i++)
      {
        for (int j = i; j < size; j++)
        {
           if (elementAt(j).compareTo(elementAt(j+1)) > 0)
           {
              swap(j, j + 1);
           }
        }
      }
    }
    
    public SinglyNode elementAt(int index)
    {
       SinglyNode temp = first;
    
       for (int i = 0, i < index; i++)
       {
          temp = temp.getNext();
       }
    
       return temp;
    }
    
    public void swap(int firstIndex, int secondIndex)
    {
       SinglyNode secondNext = elementAt(secondIndex).getNext();       
       SinglyNode second = elementAt(secondIndex);
       SinglyNode first = elementAt(first);
       SinglyNode firstPrevious = elementAt(first - 1);
    
    
       firstPrevious.setNext(second);
       first.setNext(secondNext);
       second.setNext(first);
    }
    

提交回复
热议问题