Write a C program to sort an array using bubble sort
Description: Take 5 numbers in an array and sort them in ascending order.
Hint:
- Compare each pair of neighbours. If the left one is bigger, swap them. Repeat this until the array is sorted.
C program for bubble sort
#include <stdio.h>
int main(void) {
int a[5], temp;
printf("Enter 5 numbers: ");
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("Sorted array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Output:
Output of the above program is
Enter 5 numbers: 64
25
12
22
11
Sorted array: 11 12 22 25 64
How it works
- After the first pass of the outer loop, the biggest number (64) has moved to the end. After the second pass, the second biggest is in its place, and so on.
- The inner loop runs
4 - itimes, because the lastielements are already sorted.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |