Skip to content

Commit 18ec728

Browse files
Gathrosleios
authored andcommitted
Adding C bubble sort (#78)
* Adding C bubble sort * using size_t
1 parent f688d99 commit 18ec728

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

chapters/sorting_searching/bubble/bubble_sort.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<script>
22
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
33
</script>
4-
$$
4+
$$
55
\newcommand{\d}{\mathrm{d}}
66
\newcommand{\bff}{\boldsymbol{f}}
77
\newcommand{\bfg}{\boldsymbol{g}}
@@ -25,7 +25,7 @@ $$
2525
When it comes to sorting algorithms, Bubble Sort is usually the first that comes to mind.
2626
Though it might not be the fastest tool in the shed, it's definitely straightforward to implement and is often the first sorting method new programmers think of when trying to implement a sorting method on their own.
2727

28-
Here's how it works: we go through each element in our vector and check to see if it is larger than the element to it's right.
28+
Here's how it works: we go through each element in our vector and check to see if it is larger than the element to it's right.
2929
If it is, we swap the elements and then move to the next element.
3030
In this way, we sweep through the array $$n$$ times for each element and continually swap any two adjacent elements that are improperly ordered.
3131
This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with code similar to the following:
@@ -35,6 +35,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
3535
[import:1-10, lang:"julia"](code/julia/bubble.jl)
3636
{% sample lang="cs" %}
3737
[import:9-27, lang:"csharp"](code/cs/BubbleSort.cs)
38+
{% sample lang="c" %}
39+
[import:3-21, lang:"c_cpp"](code/c/bubble_sort.c)
3840
{% sample lang="js" %}
3941
[import:1-11, lang:"javascript"](code/js/bubble.js)
4042
{% endmethod %}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <stdio.h>
2+
#include <stddef.h>
3+
4+
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) {
9+
if (array[j] > array[j + 1]) {
10+
int tmp = array[j];
11+
array[j] = array[j + 1];
12+
array[j + 1] = tmp;
13+
14+
swapped = 1;
15+
}
16+
}
17+
18+
if (!swapped) {
19+
break;
20+
}
21+
}
22+
}
23+
24+
int main() {
25+
int array[10] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
26+
27+
printf("Unsorted array:\n");
28+
for (size_t i = 0; i < 10; ++i) {
29+
printf("%d ", array[i]);
30+
}
31+
printf("\n\n");
32+
33+
bubble_sort(array, 10);
34+
35+
printf("Sorted array:\n");
36+
for (size_t i = 0; i < 10; ++i) {
37+
printf("%d ", array[i]);
38+
}
39+
printf("\n");
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)