Skip to content

Commit 46127a0

Browse files
committed
added bubble_sort_c
1 parent f033ff2 commit 46127a0

File tree

5 files changed

+52
-0
lines changed

5 files changed

+52
-0
lines changed

bubble_sort_c/question.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Make a C program to bubble sort this array of integers (smallest to biggest): {303, -909, 101, 42, 0, 42, 21, 1, 2}
2+
Expected result => {-909, 0, 1, 2, 21. 42, 42, 101, 303}

bubble_sort_c/solution/bubble_sort.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include "bubble_sort.h"
2+
3+
void swap_values(int *a, int *b)
4+
{
5+
int buffer = *a;
6+
*a = *b;
7+
*b = buffer;
8+
}
9+
10+
int *bubble_sort(int *arr, size_t arr_len)
11+
{
12+
size_t i = 0;
13+
14+
while (i++ < arr_len)
15+
{
16+
if (arr[i] < arr[i-1])
17+
{
18+
swap_values(&arr[i], &arr[i-1]);
19+
i = 0;
20+
}
21+
}
22+
return(arr);
23+
}

bubble_sort_c/solution/bubble_sort.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int *bubble_sort(int *arr, size_t arr_len);
5+
void print_array(int *arr, size_t arr_len);

bubble_sort_c/solution/main.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#include "bubble_sort.h"
2+
3+
int main(void)
4+
{
5+
int to_sort[] = {303, -909, 101, 42, 0, 42, 21, 1, 2};
6+
size_t arr_len = sizeof(to_sort) / sizeof(to_sort[0]);
7+
int *sorted = bubble_sort(to_sort, arr_len);
8+
9+
print_array(sorted, arr_len);
10+
11+
return(EXIT_SUCCESS);
12+
}

bubble_sort_c/solution/print_array.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include "bubble_sort.h"
2+
3+
void print_array(int *arr, size_t arr_len)
4+
{
5+
size_t i;
6+
7+
printf("Sorted array:\n");
8+
for (i = 0; i < arr_len; i++)
9+
printf("%d\n", arr[i]);
10+
}

0 commit comments

Comments
 (0)