BlogsDope image BlogsDope

Sorting an array using bubble sort in C

May 27, 2017 C ARRAY SORT ALGORITHM LOOP 49989

Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of an array are checked and swapped if they are in wrong order and this process is repeated until we get a sorted array. The steps of performing a bubble sort are:

  • Compare the first and the second element of the array and swap them if they are in wrong order.
  • Compare the second and the third element of the array and swap them if they are in wrong order.
  • Proceed till the last element of the array in a similar fashion.
  • Repeat all of the above steps until the array is sorted.

This will be more clear by the following visualizations.

Initial array

16 19 11 15

First iteration

16 19 11 15
16 19 11 15

SWAP

16 11 19 15
16 11 19 15

SWAP

16 11 15 19

Second iteration

16 11 15 19

SWAP

11 16 15 19
11 16 15 19

SWAP

11 15 16 19
11 15 16 19

Third iteration

11 15 16 19
11 15 16 19
11 15 16 19

No swap → Sorted → break the loop

Let’s code this up.

#include <stdio.h>
#include <math.h>

int main()
{
    int a[] = {16, 19, 11, 15, 10, 12, 14};
    int i,j;

    //repeating loop 7 (number of elements in the array) times
    for(j = 0; j<7; j++)
    {
        //initially swapped is false
        int swapped = 0;
        i = 0;
        while(i<7-1)
        {
            //comparing the adjacent elements
            if (a[i] > a[i+1])
            {
                //swapping
                int temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                //Changing the value of swapped
                swapped = 1;
            }
            i++;
        }
        //if swapped is false then the array is sorted
        //we can stop the loop
        if (!swapped)
            break;
    }

    for(i=0;i<7;i++)
        printf("%d\n",a[i]);

    return 0;
}

In this code, we are just comparing the adjacents elements and swapping them if they are not in order.  We are repeating this process 7 times (number of elements in the array). We have also assigned a variable ‘swapped’ and making it 1 (True) if any two elements get swapped in an iteration. If no interchanging of elements happens then the array is already sorted and thus no change in the value of the ‘swapped’ happens and we can break the loop.


Liked the post?
Developer and founder of CodesDope.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).