Skip to content

Commit 7f5ac13

Browse files
committed
Bubble sort
1 parent 02daf09 commit 7f5ac13

File tree

4 files changed

+79
-1
lines changed

4 files changed

+79
-1
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-main.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include "sort.h"
4+
5+
/**
6+
* main - Entry point
7+
*
8+
* Return: Always 0
9+
*/
10+
int main(void)
11+
{
12+
int array[] = {19, 48, 99, 71, 13, 52, 96, 73, 86, 7};
13+
size_t n = sizeof(array) / sizeof(array[0]);
14+
15+
print_array(array, n);
16+
printf("\n");
17+
bubble_sort(array, n);
18+
printf("\n");
19+
print_array(array, n);
20+
return (0);
21+
}

bubble

16.6 KB
Binary file not shown.

sort.h

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@
44
#include <stdio.h>
55
#include <stdlib.h>
66

7+
/**
8+
* enum bool - Enumeration of Boolean values.
9+
* @false: Equals 0.
10+
* @true: Equals 1.
11+
*/
12+
typedef enum bool
13+
{
14+
false = 0,
15+
true
16+
} bool;
17+
718
/**
819
* struct listint_s - Doubly linked list node
920
*
@@ -23,7 +34,7 @@ void print_array(const int *array, size_t size);
2334
void print_list(const listint_t *list);
2435

2536
/*sorting algorithms */
26-
37+
void bubble_sort(int *array, size_t size);
2738
void merge_sort(int *array, size_t size);
2839
void heap_sort(int *array, size_t size);
2940
void radix_sort(int *array, size_t size);

0 commit comments

Comments
 (0)