Write a C Program to Implement the Bubble Sort Algorithm

Aim:

To sort n number using Bubble sort.

Description:

• Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an array with n number of elements.
• Bubble Sort compares all the elements one by one and sorts them based on their values.
• If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.
• If we have total n elements, then we need to repeat this process for n-1 times.
• It is known as bubble sort, because with every complete iteration the largest element in the given array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.
• Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.

Following are the steps involved in bubble sort (for sorting a given array in ascending order):

1. Starting with the first element (index = 0), compare the current element with the next element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat Step 1.

Letâ€™s consider an array with values {5, 1, 6, 2, 4, 3}

Below, we have a pictorial representation of how bubble sort will sort the given array.

So as we can see in the representation above, after the first iteration, 6 is placed at the last index, which is the correct position for it.

Similarly after the second iteration, 5 will be at the second last index, and so on.

Algorithm:

1. Starting with the first element(index = 0), compare the current element with the next element of thearray.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat Step 1.

Program:

```#include <stdio.h>
int main()
{
int i, n, temp, j, arr[10];
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d", &arr [i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\n The array sorted in ascending order is :\n");
for(i=0;i<n;i++)
printf("%d\t", arr[i]);
return 0;
}```

Execution:

```Input:
10 8 9 6 7 5 4 2 3 1 10

Output:

Enter the number of elements in the array :
Enter the elements:
The array sorted in ascending order is :
1	2	3	4	5	6	7	8	9	10	```

Result:

Thus, Implement of Bubble Sort was executed successfully.