Sunday, July 5, 2020

Bubble Sort (Classical)


Algorithm: Bubble_Sort ( A, N )
Here, A is any numerical array with N number of unordered values. This algorithm will arranged the values in non-decreasing order.

Assuming, index of the array is started from 0.

Steps:
1/ Scan:= 1
2/ WHILE Scan < N, Do

     i:= 0
     WHILE i < (N-Scan), Do

       IF A(i) > A(i+1), then
         Interchange A(i) and A(i+1)
       End of IF
       i:= (i+1)

     End of WHILE (Inner Loop)
     Scan:= (Scan+1)

   End of WHILE (Outer Loop)
3/ RETURN

In this algorithm, consecutive values are comparing for their existing order, if it is not the desire order then interchanging consecutive values to maintain ordering between every consecutive values. When, all the consecutive values will be in same order, the entire set will be in the same order. As per the algorithm, in every iteration(Scan), the largest value among index 0 to index (N-Scan) will be placed in the index (N-Scan). After iteration(Scan) number i, values at index (N-i) to (N-1) will be arranged in the desired order.

It may be the case when the given data set is already arranged in the desired order, still, this algorithm will compare each consecutive values for every possible iteration(Scan) unnecessarily.

It also may be the case when the given data set is partially arranged in the desired order and after some iteration(Scan) the set may be arranged in the desire order, still, this algorithm will compare each consecutive values for every possible iteration(Scan) unnecessarily.

This problem is solved in the Modified/ Advanced Bubble Sort.