Bubble Sort
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
- Bubble sort with n element required n – 1 passes.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Advantages of the Bubble Sort:
- The bubble sort requires very little memory other than that which the array or list itself occupies.
- The bubble sort is comprised of relatively few lines of code.
- With a best-case running time of O(n), the bubble sort is good for testing whether or not a list is sorted or not. Other sorting methods often cycle through their whole sorting sequence, which often have runningtimes of O(n^2) or O(n log n) for this task.
- The same applies for data sets that have only a few items that need to be swapped a few times.
- The space requirement is at a minimum.
- The main disadvantage of the bubble sort method is the time it requires. With a running time of O(n^2), it is highly inefficient for large data sets.
- Additionally, the presence of turtles can severely slow the sort.
- The bubble sort is mostly suitable for academic teaching but not for real-life applications.
Bubble Sort Complexity:
Best :O(n2)
Worst: O(n2)
Average: O(n2)
Space Complexity: O(1)
Stability :Yes
CODE:
- #include<stdio.h>
- int swap_cnt, comp_cnt;
- void bubble_sort(int a[20], int n)
- {
- int i, temp, pass;
- comp_cnt=0, swap_cnt=0;
- for(pass=1; pass<n; pass++)
- {
- for(i=0; i<=n-pass-1; i++)
- {
- comp_cnt++;
- if(a[i]>a[i+1])
- {
- swap_cnt++;
- temp=a[i];
- a[i]=a[i+1];
- a[i+1]=temp;
- }//if
- }//inner for
- }//outer for
- }//function
- void main()
- {
- int a[20], n, i;
- printf("\n How Many Number In Array=");
- scanf("%d",&n);
- printf("Enter a element of array:");
- for(i=0; i<n; i++)
- scanf("%d", &a[i]);
- bubble_sort(a, n);
- printf("\n >>Sorted Element Are<< \n");
- for(i=0; i<n; i++)
- printf("%d\t", a[i]);
- printf("\n Number of comp_cnt are: %d \n", comp_cnt);
- printf("\n Number of swap_cnt are: %d \n", swap_cnt);
- }
Comments
Post a Comment