How to do it…

Consider an array, arr, of size len elements. We want to arrange elements of the arr array in ascending order. Here are the steps to do so:

  1. Initialize a variable, say i, to len -2.
  2. Follow and repeat steps 3 through 5 as long as i >=1.  The value of i will be decremented by 1 after every iteration, that is, i=len-2, len-3, len-4, ....1.
  1. Initialize another variable, j, to 0.
  2. Repeat step 5 to j<=i. The value of j will increase after every iteration, that is,  j=1, 2... i.
  3. If arr[j] > arr[j+1], then interchange the two values.
  4. Exit the search.

The program for sorting elements of an integer array using the bubble sort technique is as follows:

//bubblesort.c

#include <stdio.h>

#define max 20
int main() {
int arr[max], temp, len, i, j;
printf("How many values are there? ");
scanf("%d", & len);
printf("Enter %d values to sort\n", len);
for (i = 0; i < len; i++)
scanf("%d", & arr[i]);
for (i = len - 2; i >= 1; i--) {
for (j = 0; j <= i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("The sorted array is:\n");
for (i = 0; i < len; i++)
printf("%d\n", arr[i]);
return 0;
}

Now, let's go behind the scenes to understand the code better.