File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 338
338
* [ Bogo Sort] ( https://github.com/TheAlgorithms/C/blob/master/sorting/bogo_sort.c )
339
339
* [ Bubble Sort] ( https://github.com/TheAlgorithms/C/blob/master/sorting/bubble_sort.c )
340
340
* [ 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 )
341
342
* [ Bucket Sort] ( https://github.com/TheAlgorithms/C/blob/master/sorting/bucket_sort.c )
342
343
* [ Cocktail Sort] ( https://github.com/TheAlgorithms/C/blob/master/sorting/cocktail_sort.c )
343
344
* [ Comb Sort] ( https://github.com/TheAlgorithms/C/blob/master/sorting/comb_sort.c )
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments