Thursday, March 12, 2009

Bubble Sort

definition:

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 is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive.

Analysis:

Performance

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.

[edit]
Rabbits and turtles

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.

Various efforts have been made to eliminate turtles to improve upon the speed of bubble sort. Cocktail sort does pretty well, but it still retains O(n2) worst-case complexity. Comb sort compares elements large gaps apart and can move turtles extremely quickly, before proceeding to smaller and smaller gaps to smooth out the list. Its average speed is comparable to faster algorithms like Quicksort.


Sample code:

public void bubbleSort(int[] arr) { 

  boolean swapped = true; 

  int j = 0; 

  int tmp; 

  while (swapped) { 

  swapped = false; 

  j++; 

  for (int i = 0; i < arr.length - j; i++) {  

  if (arr[i] > arr[i + 1]) {  

  tmp = arr[i]; 

  arr[i] = arr[i + 1]; 

  arr[i + 1] = tmp; 

  swapped = true; 

  } 

  }  

  } 

}

Reference: http://en.wikipedia.org/wiki/Bubble_sort

                http://simpleprogrammingtutorials.com/tutorials/sorts/bubble-sort.php




No comments:

Post a Comment