Saturday, June 14, 2008

Bubble sort

Algorithm Bubblesort

This algorithm sorts the element of an array ‘A’ (having n elements) in the ascending (increasing) order. The pass counter is denoted by variable ‘P’ and the variable ‘E’ is used to count
the number of exchanges performed on any pass. The last unsorted element is referred by variable ‘l’.

Step 1 Initialization

set l ¬ n, P ¬ 1

Step 2 loop,

Repeat step 3, 4 while (P £ n – 1)

set E ¬ 0 R Initializing exchange variable.

Step 3 comparison, loop.

Repeat for i ¬ 1, l, ..... l – 1.

if (A [i] > A[i + 1]) then

set A [i] « A [i + 1] R Exchanging values.

set E ¬ E + 1

Step 4 Finish, or reduce the size.

if (E = 0) then

exit

else

set l ¬ l – 1.

No comments: