bubble (data,n)
Here DATA is an array with N element. This algorithm sorts the element in DATA.
Step 1: [Loop]
Repeat step 2 and step 3 for K=1 to N-1
Step 2: [Initialize pass pointer PTR]
Set[PTR]=1
Step 3: [Execute pass]
Repeat while PTR <=N-K
a. If DATA [PTR] > DATA [PTR+1]
Then interchange DATA [PTR] & DATA [PTR+1]
[End of if structure]
b. Set PTR =PTR+1
[End of Step 1 Loop]
Step 4: Exit
PROTOTYPE CODE:
for ( i = 1 ; i < n ; i++ )
for ( j = n-1 ; j >= i ; j-- )
if ( a[j] < a[j-1] )
swap a[j] and a[j-1]
FUNCTIONING DIAGRAM EXAMPLE:
COMPLEXITY:
The bubble sort method of sorting an array of size n requires (n-1) passes and (n-1)
comparisons on each pass. Thus the total number of comparisons is (n-1) * (n-1) = n2
– 2n + 1, which is O(n2). Therefore bubble sort is very inefficient when there are more
elements to sorting.
Aso, The time for a sorting algorithm is measured in terms of the number of comparisons. The number f(n) of comparisons in the bubble sort is easily computed. There are n-1 comparisons during the first pass, which places the largest element in the last position; there are n-2 comparisons in the second step, which places the second largest element in the next to last position and so on.
F(n)=(n-1)+(n-2)+….+2+1=n(n-1)/2=n^2/2+0(n)=0(n^2)
The time required to execute the bubble sort algorithm is proportional to n^2, Where n is the number of input items.
STABILITY:
Bubble Sort This is stable because no item is swapped past another unless they are in the wrong order. So items with identical keys will have their original order preserved.
0 Comments
Doubts? Please let our team know So that we can serve you better.