C Program to Sort Array in Ascending Order – Bubble Sort

C Program to Sort Array in Ascending Order – Bubble Sort

Just like as a bubble in water goes from bottom to top, this sort is named for the way smaller or larger elements “bubble” to the top of the list depending on the order of sorting. Bubble sort simply swaps adjacent items if they are incorrectly ordered.  It continues moving down the list, and will keep on going until everything is sorted.

In bubble sort, total number of cycles/round is n-1 (where n is the total number of elements).

In each cycle, we compare two consecutive numbers, if first number is greater than second , then interchange the values,

consider a array of 6 elements,  as 78  55  16  85  29   17

In first cycle,

Compare first consecutive Numbers, which is 78 & 55,

is 78 is greater than 55 ? if Yes then swap (i.e interchange the values) so at 1st position 55 and 2nd position 78

55    78   16    85    29  17

Compare next consecutive Numbers, which is 78 & 16,

is 78 is greater than 16 ? if Yes then swap (i.e interchange the values) so at 1st position 16 and 2nd position 78

55   16    78    85   29   17

Compare next consecutive Numbers, which is 78 & 85,

is 78 is greater than 85 ? No so do not swap the values.

55   16   78    85   29    17

Compare next consecutive Numbers, which is 85 & 29,

is 85 is greater than 29 ? if Yes then swap (i.e interchange the values) so at 1st position 29 and 2nd position 85

55   16    78   29   85    17

Compare next consecutive Numbers, which is 85 & 17,

is 85 is greater than 17 ? if Yes then swap (i.e interchange the values) so at 1st position 17 and 2nd position 85

55   16    78   29    17    85

so in first cycle , we placed largest number at last. Now  array  55    16    78   29    17   85

Now skip last position of array and follow same procedure.

after second cycle : array is  16  55  29  17  78  85

after third cycle : array is  16  29  17   55  78  85

after fourth cycle : array is  16  17  29  55  78  85

after fifth cycle : array is  16  17  29  55  78  85

after sixth cycle : array is  16  17  29  55  78  85

C Program Code Ascending Order Bubble Sort.c (23 downloads)
Output
output-c-program-ascending-order
output-c-program-ascending-order