Bubble Sort
Completed
Read n integers and sort them ascending with bubble sort. Print the sorted array.
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
6 5 2 9 1 5 6
Output
1 2 5 5 6 9
Editor
C
Hints
Swap neighbours that are in the wrong order; repeat.
Solution explanation
After each pass the largest remaining value has "bubbled" to the end.
Show solution
#include <stdio.h>
int main() {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int end = n - 1; end > 0; end--) {
for (int i = 0; i < end; i++) {
if (a[i] > a[i + 1]) {
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
for (int i = 0; i < n; i++) {
printf("%d", a[i]);
if (i < n - 1) printf(" ");
}
printf("\n");
return 0;
}