+ 1

What's wrong with this code?

#include <stdio.h> void bubble_sort (int a[], int n) { int i = 0, j = 0, tmp; for (i = 0; i < n; i++) { // loop n times - 1 per element for (j = 0; j < n - i - 1; j++) { // last i elements are sorted already if (a[j] > a[j + 1]) { // swop if order is broken tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } }} main() { int a[100], n, i, d, swap; printf("Enter number of elements in the array:\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); bubble_sort(a, n); printf("Printing the sorted array:\n"); for (i = 0; i < n; i++) printf("%d\n", a[i]); return 0;}

23rd Jan 2019, 1:45 PM
Lilit
Lilit - avatar
2 ответов
+ 7
Here's the same code but a little bit more readable: #include <stdio.h> void bubble_sort (int a[], int n){ int i = 0, j = 0, tmp; for (i = 0; i < n; i++) { // loop n times - 1 per element for (j = 0; j < n - i - 1; j++){ // last i elements are sorted already if (a[j] > a[j + 1]) { // swop if order is broken tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } main() { int a[100], n, i, d, swap; printf("Enter number of elements in the array:\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); bubble_sort(a, n); printf("Printing the sorted array:\n"); for (i = 0; i < n; i++) printf("%d\n", a[i]); return 0; } It is the exactly same one as yours, and it works just fine. Maybe the input method is wrong: make sure you input your numbers as such: 3 3 2 1 Another example: 5 6 4 3 1 2 8
23rd Jan 2019, 1:53 PM
Uni
Uni - avatar
+ 4
Could you save your code on Sololearn and paste the link here, please?
23rd Jan 2019, 1:53 PM
Zen
Zen - avatar