(Java) Bubble Sort in Linked List

Posted: July 30, 2008 in Java, Programming
Tags: , ,

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Let us take the array (For example of bubble sort, we use array not linked list, it just same) of numbers “5 1 4 2 8”, and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.

First Pass:
( 5 1 4 2 8 ) to ( 1 5 4 2 8 ) Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) to ( 1 4 5 2 8 )
( 1 4 5 2 8 ) to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) to ( 1 4 2 5 8 ) Now, since these elements are already in order, algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. Algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) to ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.

Bubble function implementation in linked list:

static void bubbleSort(int lenght)
{
Node n;
boolean isSorted=false;

for(int i=lenght-1; i>1 && isSorted==false; i–)
{
for(int j=0; jDownload Source Code

The source contain three files:
Main.java (where contain bubblesort function)
Node.java
LinkedList.java

(some of content was taken from Wikipedia)

Comments
  1. Random T. says:

    The topic is quite trendy on the Internet right now. What do you pay attention to while choosing what to write ?

  2. gulbax says:

    ijin ngunduh buat tugas pendahuluan

  3. gulbax says:

    salah filenya zer

  4. misugijunz says:

    pada dasarnya buble sort itu blind algorithm…

    dengan menambahkan boolean isFalse dan diiterasi dari belakang akan menaikkan performa :D…

  5. justin says:

    pusing saya mikirin struktur data…
    ada solusi nggak?

  6. Thomas says:

    It was fun to read this article:) Thanks, very interesting.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s