# C Program to Sort an Array Using Bubble Sort

Sorting is a procedure in which the given elements are arranged in ascending or descending order. For example if the elements of an array are –

5, 11, 15, 8, 7, 54, 63, 44

After sorting these elements in ascending order, the elements would be –

5, 7, 8, 11, 15, 44, 54, 63

What is Bubble Sort is :

Bubble sort proceeds by scanning the list and exchanging the adjacent elements if they are out of order with respect to each other. It compares each element with its adjacent element and swaps them if they are not in order i.e. arr[j] will be compared with arr[j+1] and if arr[j]>arr[j+1] then they will be swapped.

Let’s See the Program for Bubble Sort ►►

```#include<stdio.h>
#include<conio.h>

void main()
{
int size,arr[100],i,j,min,temp;

printf("Enter the Number of Elements : ");
scanf("%d",&size);

printf("\nEnter the elements of the Array : ");

for(int i=0;i<size;i++) {
printf("\nArray[%d] = ",i+1);
scanf("%d",&arr[i]);
}

/* Bubble Sort */
for(i=0; i<(size-1) ;i++)
{

for(j=0; j<(size-1-i); j++)
{
if(arr[j]>arrr[j+1])
{
temp=ar[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

printf("\nSorted List is : \n");

for(i=0;i<size;i++)
printf("%d\t",arr[i]);

getch();

}```

Explanation ►►  Each iteration of outer for loop corresponds to a single pass. After first pass the largest element will be at its proper position in the array i.e. (size-1)th position, after second pass the second largest element will be placed at its proper position i.e. (size-2)th position. Similarly after each pass the larger elements will be moved to the end of the list and placed at their proper positions. That is why in inner for loop we run the loop till the value of variable j is less than size-1-i (j<size-1-i) because at the end of the list there will be the larger elements so we don’t need to compare with them. And we run the outer for loop till the value of i is less than size-1 because the statement (arr[j]>arr[j+1]) compare the value with the next one so if we use the condition (i<size) then the last element will be compare with any other location containing the garbage value that will cause an unpredictible result.