Bubble Sort Algorithm

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.Bubble sort has worst-case and average complexity both О(n²), where n is the number of items being sorted. There exist many sorting algorithms with the substantially better worst-case or average complexity of O(n log n). Even other О(n²) sorting algorithms, such as insertion sort,tend to have better performance than bubble sort. Therefore bubble sort is not a practical sorting algorithm when n is large.The positions of the elements in bubble sort will play a large part in determining its performance. Large elements at the beginning of the list do not pose a problem, as they are quickly swapped. Small elements towards the end, however, move to the beginning extremely slowly. This has led to these types of elements being named rabbits and turtles, respectively

Example

Let us take the array 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 ) --- ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) --- ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) --- ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) --- ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) --- ( 1 4 2 5 8 )
( 1 4 2 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 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 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.

Source Code

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int x;

// Bubble Sort Algorithm
public void sortArray()
{
int i;
int j;
int temp;

for( i = (x - 1); i >= 0; i-- )
{
for( j = 1; j <= i; j++ ) { if( a[j-1] > a[j] )
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}

0 comments:

Template by - Mathew | Mux99