Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
bubble_sort_2.c File Reference

implementation of Bubble sort algorithm More...

#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
Include dependency graph for bubble_sort_2.c:

Macros

#define MAX   20
 for rand() calls for assert(<expr>)
 

Functions

void bubble_sort (int *array_sort)
 Bubble sort implementation.
 
static void test ()
 Test implementations.
 
int main ()
 Main function.
 

Detailed Description

implementation of Bubble sort algorithm

worst-case: O(n^2) best-case: O(n) average-complexity: O(n^2)

Author
Unknown author
Gabriel Fioravante

Macro Definition Documentation

◆ MAX

#define MAX   20

for rand() calls for assert(<expr>)

for boolean values: true, false

Function Documentation

◆ bubble_sort()

void bubble_sort ( int *  array_sort)

Bubble sort implementation.

Parameters
array_sortthe array to be sorted
Returns
void
25{
26 bool is_sorted = false;
27
28 /* keep iterating over entire array
29 * and swaping elements out of order
30 * until it is sorted */
31 while (!is_sorted)
32 {
33 is_sorted = true;
34
35 /* iterate over all elements */
36 for (int i = 0; i < MAX - 1; i++)
37 {
38 /* check if adjacent elements are out of order */
39 if (array_sort[i] > array_sort[i + 1])
40 {
41 /* swap elements */
42 int change_place = array_sort[i];
43 array_sort[i] = array_sort[i + 1];
44 array_sort[i + 1] = change_place;
45 /* elements out of order were found
46 * so we reset the flag to keep ordering
47 * until no swap operations are executed */
48 is_sorted = false;
49 }
50 }
51 }
52}
#define MAX
for rand() calls for assert(<expr>)
Definition bubble_sort_2.c:17

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
84{
85 test(); // run self-test implementations
86 return 0;
87}
static void test()
Test implementations.
Definition bubble_sort_2.c:58
Here is the call graph for this function:

◆ test()

static void test ( void  )
static

Test implementations.

Returns
void
58 {
59 /* simple int array for testing */
60 int array_sort[MAX] = {0};
61
62 /* populate our test array with
63 * random integer numbers */
64 for (int i = 0; i < MAX; i++)
65 {
66 array_sort[i] = rand() % 101;
67 }
68
69 /* sort array */
70 bubble_sort(array_sort);
71
72 /* check if array ir correctly ordered */
73 for (int i = 0; i < MAX - 1; i++)
74 {
75 assert(array_sort[i] <= array_sort[i+1]);
76 }
77}
void bubble_sort(int *array_sort)
Bubble sort implementation.
Definition bubble_sort_2.c:24
Here is the call graph for this function: