Bubble Sort in C
Q. Write a C program for bubble sort.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[100], n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the integers: ");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (i = 0 ; i < n - 1; i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
getch();
}
Q. Write an algorithm to bubble sort in C.
1. Start
2. Input the number of elements `n`.
3. Initialize an array `a` of size `n`.
4. Input the elements of the array:
- For each index `i` from `0` to `n-1`:
- Read the element `a[i]`.
5. Perform Bubble Sort:
- For `i` from `0` to `n-2`:
- For `j` from `0` to `n-i-2`:
- If `a[j] > a[j+1]` then
- Swap `a[j]` and `a[j+1]`.
6. Print the sorted array:
- For each index `i` from `0` to `n-1`:
- Print `a[i]`.
7. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com