Skip to content

Commit 3dc9472

Browse files
realDuYuanChaogithub-actions
andauthored
Bubble sort recursion (#574)
* bubble sort by recursion * updating DIRECTORY.md * fix compile error Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 5d9bf07 commit 3dc9472

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@
338338
* [Bogo Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/bogo_sort.c)
339339
* [Bubble Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/bubble_sort.c)
340340
* [Bubble Sort 2](https://github.com/TheAlgorithms/C/blob/master/sorting/bubble_sort_2.c)
341+
* [Bubble Sort Recursion](https://github.com/TheAlgorithms/C/blob/master/sorting/bubble_sort_recursion.c)
341342
* [Bucket Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/bucket_sort.c)
342343
* [Cocktail Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/cocktail_sort.c)
343344
* [Comb Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/comb_sort.c)

sorting/bubble_sort_recursion.c

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* @file
3+
* @brief [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) algorithm
4+
* implementation using recursion.
5+
*/
6+
#include <assert.h>
7+
#include <stdbool.h>
8+
#include <stdio.h>
9+
#include <stdlib.h>
10+
#include <time.h>
11+
12+
/**
13+
* Swapped two numbers using pointer
14+
* @param first first pointer of first number
15+
* @param second second pointer of second number
16+
*/
17+
void swap(int *first, int *second)
18+
{
19+
int temp = *first;
20+
*first = *second;
21+
*second = temp;
22+
}
23+
24+
/**
25+
* Bubble sort algorithm implements using recursion
26+
* @param arr array to be sorted
27+
* @param size size of array
28+
*/
29+
void bubbleSort(int *arr, int size)
30+
{
31+
if (size == 1)
32+
{
33+
return;
34+
}
35+
bool swapped = false;
36+
for (int i = 0; i < size - 1; ++i)
37+
{
38+
if (arr[i] > arr[i + 1])
39+
{
40+
swap(arr + i, arr + i + 1);
41+
swapped = true;
42+
}
43+
}
44+
if (swapped)
45+
{
46+
bubbleSort(arr, size - 1);
47+
}
48+
}
49+
50+
/**
51+
* Test function
52+
*/
53+
void test()
54+
{
55+
const int size = 10;
56+
int *arr = (int *)calloc(size, sizeof(int));
57+
58+
/* generate size random numbers from 0 to 100 */
59+
for (int i = 0; i < size; i++)
60+
{
61+
arr[i] = rand() % 100;
62+
}
63+
bubbleSort(arr, size);
64+
for (int i = 0; i < size - 1; ++i)
65+
{
66+
assert(arr[i] <= arr[i + 1]);
67+
}
68+
free(arr);
69+
}
70+
71+
/** Driver Code */
72+
int main()
73+
{
74+
/* Intializes random number generator */
75+
srand(time(NULL));
76+
test();
77+
return 0;
78+
}

0 commit comments

Comments
 (0)