Skip to content

Commit 8437b5f

Browse files
Write a function that sorts an array of integers in ascending order using the Bubble sort algorithm Prototype: void bubble_sort(int *array, size_t size);
1 parent 4373123 commit 8437b5f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

0-bubble_sort.c

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include "sort.h"
2+
3+
/**
4+
* swap_ints - Swap two integers in an array.
5+
* @a: The first integer to swap.
6+
* @b: The second integer to swap.
7+
*/
8+
void swap_ints(int *a, int *b)
9+
{
10+
int tmp;
11+
12+
tmp = *a;
13+
*a = *b;
14+
*b = tmp;
15+
}
16+
17+
/**
18+
* bubble_sort - Sort an array of integers in ascending order.
19+
* @array: An array of integers to sort.
20+
* @size: The size of the array.
21+
*
22+
* Description: Prints the array after each swap.
23+
*/
24+
void bubble_sort(int *array, size_t size)
25+
{
26+
size_t i, len = size;
27+
bool bubbly = false;
28+
29+
if (array == NULL || size < 2)
30+
return;
31+
32+
while (bubbly == false)
33+
{
34+
bubbly = true;
35+
for (i = 0; i < len - 1; i++)
36+
{
37+
if (array[i] > array[i + 1])
38+
{
39+
swap_ints(array + i, array + i + 1);
40+
print_array(array, size);
41+
bubbly = false;
42+
}
43+
}
44+
len--;
45+
}
46+
}

0 commit comments

Comments
 (0)