Skip to content

Commit 8b0e8f1

Browse files
authored
Merge pull request #254 from antonte/bubble-sort-c
Match bubble sort C implementation with Julia
2 parents 1fb836c + 6db8c48 commit 8b0e8f1

File tree

2 files changed

+16
-23
lines changed

2 files changed

+16
-23
lines changed

chapters/algorithms/bubble_sort/bubble_sort.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
1313
{% sample lang="cs" %}
1414
[import:9-27, lang:"csharp"](code/csharp/BubbleSort.cs)
1515
{% sample lang="c" %}
16-
[import:4-22, lang:"c_cpp"](code/c/bubble_sort.c)
16+
[import:11-21, lang:"c_cpp"](code/c/bubble_sort.c)
1717
{% sample lang="java" %}
1818
[import:2-12, lang:"java"](code/java/bubble.java)
1919
{% sample lang="js" %}
Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,35 @@
11
#include <stdio.h>
2-
#include <stddef.h>
2+
3+
void print_range(int *array, size_t n) {
4+
for (size_t i = 0; i < n; ++i) {
5+
printf("%d ", array[i]);
6+
}
7+
printf("\n");
8+
}
39

410
void bubble_sort(int *array, size_t n) {
5-
int swapped = 0;
6-
for (size_t i = 0; i < n - 1; ++i) {
7-
swapped = 0;
8-
for (size_t j = 0; j < n - i - 1; ++j) {
11+
for (size_t i = 0; i < n; ++i) {
12+
for (size_t j = 0; j < n - 1; ++j) {
913
if (array[j] > array[j + 1]) {
1014
int tmp = array[j];
1115
array[j] = array[j + 1];
1216
array[j + 1] = tmp;
13-
14-
swapped = 1;
1517
}
1618
}
17-
18-
if (!swapped) {
19-
break;
20-
}
2119
}
2220
}
2321

2422
int main() {
25-
int array[10] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
23+
int array[] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
24+
size_t N = sizeof(array) / sizeof(*array);
2625

2726
printf("Unsorted array:\n");
28-
for (size_t i = 0; i < 10; ++i) {
29-
printf("%d ", array[i]);
30-
}
31-
printf("\n\n");
27+
print_range(array, N);
3228

33-
bubble_sort(array, 10);
29+
bubble_sort(array, N);
3430

35-
printf("Sorted array:\n");
36-
for (size_t i = 0; i < 10; ++i) {
37-
printf("%d ", array[i]);
38-
}
39-
printf("\n");
31+
printf("\nSorted array:\n");
32+
print_range(array, N);
4033

4134
return 0;
4235
}

0 commit comments

Comments
 (0)