Skip to content

Commit 3c38da3

Browse files
committed
Match bubble sort C implementation with Julia
1 parent 0d89be5 commit 3c38da3

File tree

2 files changed

+16
-22
lines changed

2 files changed

+16
-22
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 & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,36 @@
11
#include <stdio.h>
22
#include <stddef.h>
33

4+
void print_range(int *array, size_t n) {
5+
for (size_t i = 0; i < n; ++i) {
6+
printf("%d ", array[i]);
7+
}
8+
printf("\n");
9+
}
10+
411
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) {
12+
for (size_t i = 0; i < n; ++i) {
13+
for (size_t j = 0; j < n - 1; ++j) {
914
if (array[j] > array[j + 1]) {
1015
int tmp = array[j];
1116
array[j] = array[j + 1];
1217
array[j + 1] = tmp;
13-
14-
swapped = 1;
1518
}
1619
}
17-
18-
if (!swapped) {
19-
break;
20-
}
2120
}
2221
}
2322

2423
int main() {
25-
int array[10] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
24+
const int N = 10;
25+
int array[N] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
2626

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

33-
bubble_sort(array, 10);
30+
bubble_sort(array, N);
3431

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

4135
return 0;
4236
}

0 commit comments

Comments
 (0)