C – Bubble Sort

Bubble Sort:

  • Simple sorting technique to arrange elements either in Ascending order or Descending order.
  • In Bubble sort, the index element compares with the next element and swapping them if required.
  • For each pass(inner loop completion) highest element bubbled to last location.
  • This process continuous until the complete array get sorted.
#include <stdio.h>
void sort(int array[], int size)
{
            int i, j, temp;
            for (i = 0; i < size – 1; i++)
            {
                        for (j = 0; j < size – i – 1; j++)
                        {
                                    if (array[j] > array[j+1])
                                    {
                                                temp = array[j];
                                                array[j] = array[j+1];
                                                array[j+1] = temp;
                                    }
                        }
            }
}
 
int main()
{
            int i, size, array[100];
            printf(“Enter the number of elements in the array: “);
            scanf(“%d”, &size);
 
            printf(“Enter %d elements:\n”, size);
            for (i = 0; i < size; i++)
            {
                        scanf(“%d”, &array[i]);
            }
 
            sort(array, size);
 
            printf(“\nSorted array in ascending order:\n”);
            for (i = 0; i < size; i++)
            {
                        printf(“%d “, array[i]);
            }
 
            return 0;
}
Scroll to Top