You are here

C program for bubble sort

C program for bubble sort: C programming code for bubble sort to sort numbers or arrange them in ascending order. You can modify it to print numbers in descending order.You can also sort strings using Bubble sort, it is less efficient as its average and worst case complexity is high, there are many other fast sorting algorithms like quick-sort, heap-sort, etc. Sorting simplifies problem-solving in computer programming.

Bubble sort algorithm implementation in C

  1. /* Bubble sort code */
  2.  
  3. #include <stdio.h>
  4.  
  5. int main()
  6. {
  7.   int array[100], n, c, d, swap;
  8.  
  9.   printf("Enter number of elements\n");
  10.   scanf("%d", &n);
  11.  
  12.   printf("Enter %d integers\n", n);
  13.  
  14.   for (c = 0; c < n; c++)
  15.     scanf("%d", &array[c]);
  16.  
  17.   for (c = 0 ; c < n - 1; c++)
  18.   {
  19.     for (d = 0 ; d < n - c - 1; d++)
  20.     {
  21.       if (array[d] > array[d+1]) /* For decreasing order use < */
  22.       {
  23.         swap       = array[d];
  24.         array[d]   = array[d+1];
  25.         array[d+1] = swap;
  26.       }
  27.     }
  28.   }
  29.  
  30.   printf("Sorted list in ascending order:\n");
  31.  
  32.   for (c = 0; c < n; c++)
  33.      printf("%d\n", array[c]);
  34.  
  35.   return 0;
  36. }

Output of program:
Bubble sort C program output

Download Bubble sort program.

Bubble sort in C language using function

  1. #include <stdio.h>
  2.  
  3. void bubble_sort(long [], long);
  4.  
  5. int main()
  6. {
  7.   long array[100], n, c, d, swap;
  8.  
  9.   printf("Enter number of elements\n");
  10.   scanf("%ld", &n);
  11.  
  12.   printf("Enter %ld integers\n", n);
  13.  
  14.   for (c = 0; c < n; c++)
  15.     scanf("%ld", &array[c]);
  16.  
  17.   bubble_sort(array, n);
  18.  
  19.   printf("Sorted list in ascending order:\n");
  20.  
  21.   for (c = 0; c < n; c++)
  22.      printf("%ld\n", array[c]);
  23.  
  24.   return 0;
  25. }
  26.  
  27. void bubble_sort(long list[], long n)
  28. {
  29.   long c, d, t;
  30.  
  31.   for (c = 0 ; c < n - 1; c++)
  32.   {
  33.     for (d = 0 ; d < n - c - 1; d++)
  34.     {
  35.       if (list[d] > list[d+1])
  36.       {
  37.         /* Swapping */
  38.  
  39.         t         = list[d];
  40.         list[d]   = list[d+1];
  41.         list[d+1] = t;
  42.       }
  43.     }
  44.   }
  45. }