Kamis, 07 Juli 2011

BUBBLE 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.

Algorithm

  1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
  2. If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.

Example, sort (5, 1, 12, -5, 16) using bubble sort
Sorting Process :
5  1  12  -5  16  --> unsorted
5  1  12  -5  16 --> 5 > 1, swap
5  12  -5  16 --> 5 < 12, ok
1  5  12  -5  16 --> 12 > -5, swap
1  5  -5  12  16 --> 12 < 16, ok

1  5  -5  12  16 --> 1 < 5, ok
5  -5  12  16 --> 5 > -5, swap
1 -5   5  12  16 --> 5 < 12, ok

1  -5  5  12  16 --> 1 > -5, swap
-5  1  5  12  16 --> 1 < 5, ok

-5  1  5  12  16 --> -5 < 1, ok

-5  1  5  12  16 --> sorted

Tidak ada komentar:

Posting Komentar