Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Bubble sort is a simple sorting algorithm.

This sorting algorithm is comparison-based


algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets

Lets try to understand the pseudo code with an example: A [ ] = { 7, 4, 5, 2}

In step 1, 7 is compared with 4. Since 7>4, 7 is moved ahead of 4. Since all the other elements
are of a lesser value than 7, 7 is moved to the end of the array.

Now the array is A[]={4,5,2,7}.

In step 2, 4 is compared with 5. Since 5>4 and both 4 and 5 are in ascending order, these


elements are not swapped. However, when 5 is compared with 2, 5>2 and these elements are in
descending order. Therefore, 5and 2 are swapped.
Now the array is A[]={4,2,5,7}.
In step 3, the element 4 is compared with 2. Since 4>2 and the elements are in descending
order, 4 and 2 are swapped.
The sorted array is A[]={2,4,5,7}.
Complexity: 
The complexity of bubble sort is O(n2) in both worst and average cases, because the entire array
needs to be iterated for every element.

Program

1. #include <stdio.h>
2.  
3. int main()
4. {
5.   int array[100], n, c, d, swap;
6.  

Prof. R. G. Sonkamble
7.   printf("Enter number of elements\n");
8.   scanf("%d", &n);
9.  
10.   printf("Enter %d integers\n", n);
11.  
12.   for (c = 0; c < n; c++)
13.     scanf("%d", &array[c]);
14.  
15.   for (c = 0 ; c < n - 1; c++)
16.   {
17.     for (d = 0 ; d < n - c - 1; d++)
18.     {
19.       if (array[d] > array[d+1]) /* For decreasing order use
< */
20.       {
21.         swap       = array[d];
22.         array[d]   = array[d+1];
23.         array[d+1] = swap;
24.       }
25.     }
26.   }
27.  
28.   printf("Sorted list in ascending order:\n");
29.  
30.   for (c = 0; c < n; c++)
31.      printf("%d\n", array[c]);
32.  
33.   return 0;
34. }

Prof. R. G. Sonkamble

You might also like