Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
bubble_sort.c File Reference

Bubble sort algorithm implementation More...

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for bubble_sort.c:

Functions

void display (const int *arr, int n)
 Display elements of array. More...
 
void swap (int *first, int *second)
 Swap two values by using pointer. More...
 
void bubbleSort (int *arr, int size)
 Bubble sort algorithm implementation. More...
 
void test ()
 Test function.
 
int main (int argc, const char *argv[])
 Driver Code.
 

Detailed Description

Bubble sort algorithm implementation

Function Documentation

◆ bubbleSort()

void bubbleSort ( int *  arr,
int  size 
)

Bubble sort algorithm implementation.

Parameters
arrarray to be sorted
sizesize of array
44 {
45  for (int i = 0; i < size - 1; i++)
46  { /* for each array index */
47  bool swapped = false; /* flag to check if any changes had to be made */
48  /* perform iterations until no more changes were made or outer loop
49  executed for all array indices */
50  for (int j = 0; j < size - 1 - i; j++)
51  { /* for each element in the array */
52  if (arr[j] > arr[j + 1])
53  { /* if the order of successive elements needs update */
54  swap(&arr[j], &arr[j + 1]);
55  swapped = true; /* set flag */
56  }
57  }
58  if (!swapped)
59  {
60  /* since no more updates we made, the array is already sorted
61  this is an optimization for early termination */
62  break;
63  }
64  }
65 }
Here is the call graph for this function:

◆ display()

void display ( const int *  arr,
int  n 
)

Display elements of array.

Parameters
arrarray to be display
nlength of array
18 {
19  for (int i = 0; i < n; i++)
20  {
21  printf("%d ", arr[i]);
22  }
23  printf("\n");
24 }

◆ swap()

void swap ( int *  first,
int *  second 
)

Swap two values by using pointer.

Parameters
firstfirst pointer of first number
secondsecond pointer of second number
32 {
33  int temp = *first;
34  *first = *second;
35  *second = temp;
36 }
swap
void swap(int *first, int *second)
Swap two values by using pointer.
Definition: bubble_sort.c:31