Sunday, October 14, 2007

sorting

Like selection sort, which you saw in the previous article, sorting using bubble sort technique is accomplished through several rounds of comparison. To sort the array containing 5 elements, you might need at least 4 rounds of comparison. In each round again there will be several comparisons. The sorting process is as follows:

1. Select the first element in the array and compare it with the second. If the second element is less than the first element, then interchange their positions. Now compare second and third and interchange if third is less than second. Continue this process of comparison and interchanging till the last element in the array. This marks the end of, the first round. After this round you will find the biggest element in the array at the last position.

2. Select the first element again in the array and repeat the process of comparison and interchanging as above. This completes the second round. After this round you will find the second largest element in the last but one position.

3. Note that during each round the largest elements will go to the end of the array. So you should write your program in such a way that in each round of comparison these elements should not be taken into account. Unlike selection sort here the successive elements are compared during every round and that’s the reason why this technique is called bubble sorting.


Examine the following figures to understand the sorting process for a set of 4 numbers — 8,5,2, and 3


Round-I
Here, since 8 is greater than 5, they
interchange their positions.

Here, since 8 is greater than 2, they
interchange their positions.
Here, since 8 is greater than 3, they
interchange their positions. Observe that the
highest value has come to the last position.



Round – II

Here, since 5 is greater than 2, they
interchange their positions.

Here, since 5 is greater than 3, they
interchange their positions.

Observe that the second highest value has
reached the last but one position in the array.



Round - III

Here, since 2 is not greater than 3, they
will not interchange their positions.

This is the final sorted array.

No comments: