Bubblesort-Algorithm
Bubblesort-Algorithm
SEARCHING
Sorting
The process of arranging the elements in a list in either ascending
or
descending order.
Types of Sorting:
Bubble Sort
Insertion Sort
Selection Sort
Merge Sort
Quick sort
Heap Sort
Radix Sort
Bubble
Sorting
Bubble sort is the easiest sorting algorithm to implement.
It is inspired by observing the behaviour of air bubbles over
foam.
It is an in-place sorting algorithm.
It uses no auxiliary data structures (extra space) while sorting.
How Bubble Sort Works?
Step-01:
We have pass=1 and i=0.
We perform the comparison A[0] > A[1] and swaps if the
0th element is greater than the 1th element.
Since 6 > 2, so we swap the two elements.
Bubble Sort
▸ Step-02: Example-
▸
▸ We have pass=1 and i=1.
▸ We perform the comparison A[1] > A[2] and swaps if the 1th element is
greater than the 2th element.
▸ Since 6 < 11, so no swapping is required.
Bubble Sort
Example-
▸ Step-03:
▸
▸ We have pass=1 and i=2.
▸ We perform the comparison A[2] > A[3] and swaps if the 2nd element is
greater than the 3rd element.
▸ Since 11 > 7, so we swap the two elements.
Bubble Sort
Example-
▸ Step-04:
▸
▸ We have pass=1 and i=3.
▸ We perform the comparison A[3] > A[4] and swaps if the 3rd element
is
greater than the 4th element.
▸ Since 11 > 5, so we swap the two elements.
Finally after the first pass, we see that the largest element 11 reaches its correct
position
Bubble Sort
Example-
▸ Step-05:
▸ Similarly after pass=2, element 7 reaches its correct
▸ The modified array after pass=2 is shown
position.
below-
▸ Step-06:
▸ Similarly after pass=3, element 6 reaches its
correct
position.
▸ The modified array after pass=3 is shown below-
Bubble Sort
▸ Step-07: Example-
▸ No further improvement is done in
pass=4.
▸ This is because at this point, elements 2 and 5 are already present at their correct
positions.
▸ The loop terminates after pass=4.
▸ Finally, the array after pass=4 is shown below-
Optimization Of Bubble Sort
Algorithm-
▸ If the array gets sorted after a few passes like one or two, then
ideally the algorithm should terminate.
▸ But still the above algorithm executes the remaining passes which
costsextra comparisons. for (int pass=1 ; pass<=n-1 ; ++pass)
{
flag=0 // flag denotes are there any swaps done in pass
for (int i=0 ; i<=n-2 ; ++i)
{
if(A[i] > A[i+1])
{
swap(i,i+1,A);
flag=1 // After swap, set flag to 1
}
}
if(flag == 0) break; // No swaps indicates we can terminate loop
}
void swap(int x, int y, int[] A)
{
int temp = A[x];
A[x] = A[y];
A[y] = temp;
return;
}
Optimization Of Bubble Sort
Algorithm-