October 7, 2022

Bubble Sorting in C Programming

BUBBLE SORTING: One of the characteristics of this sort is that it is easy to understand and program it is probably the least efficient. The basic idea underlying the bubble sort is to pass through the file sequentially several times. Each pass consists of comparing each element in the file with its successor and interchanging the two elements if they are not in proper order. The method is called the bubble sort because each number slowly “bubbles” up to its proper position.

In this sort, the number of interchanges cannot be greater than the number of comparisons it is likely that it is the number of interchanges rather than the number of comparisons that takes up most times in the program’s execution. The only redeeming features of the bubble sort are that it requires little additional space (one additional record to hold the temporary value for interchanging and several simple integer variables) and that it is O (N) in the case that the file is completely sorted (or most completely sorted).

This follows from the observation that only one pass of (N – 1) comparisons (and no interchanges) is necessary to establish that a sorted file is sorted. The bubble sort technique possesses one very important property- ” Once there is no swapping of elements in a particular pass, there will be no further swapping of elements in the subsequent passes. This property can be exploited to reduce unnecessary (redundant) passes. For this purpose we can use a flag to determine if any under interchange has taken place, if yes only then proceed with the next pass; otherwise, stop. The first pass makes an n – 1 comparison, the second pass makes n – 2 and so on. So total comparisons are (N – 1) + (N -2) + (N – 3) + + 2 + 1 = N (N – 1) / 2 = O(N^2).

bubble sorting in c programming

Algorithm Bubble sorting in c programming.

Here A is an array with N elements. This algorithm sorts the array A with N elements in ascending order.
1. Set SWAP: = True.
2. Set I : = 1.
3. Repeat Steps 4 to 6 while I < N AND SWAP = True :
4.      Set SWAP: = False.
5.      Repeat Steps for J: = 1 to N – 1 :
                If A [J] > A [J + 1], then :
                        Set TEMP : = A [J]
                        (b) Set A [J] : = A [J + 1].
                        (c) Set A [J + 1] : = TEMP.
                        (d) Set SWAP : = True.
                [End of If structure.]
        [End of Step 5 loop.]
6.      Set I : = I + 1.
   [End of Step 3 loop.]
7. Return.

Bubble Sorting program in C.

#define SIZE 10
void bubble_sort(int [], int);

void main()
int a[SIZE],n,i;
printf("Enter how many elements");

/*input array*/

printf("Enter element %d ",i+1);


/*Output Array */

printf("%d ",a[i]);



void bubble_sort(int a[], int n)
int i,j,SWAP,t;

while(i < n && swap == 1)
SWAP = 0;
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
SWAP = 1;

Leave a Reply

Your email address will not be published. Required fields are marked *