Bubble sort algorithm implementation
More...
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
|
void | display (const int *arr, int n) |
| Display elements of array.
|
|
void | swap (int *first, int *second) |
| Swap two values by using pointer.
|
|
void | bubbleSort (int *arr, int size) |
| Bubble sort algorithm implementation.
|
|
void | test () |
| Test function.
|
|
int | main (int argc, const char *argv[]) |
| Driver Code.
|
|
Bubble sort algorithm implementation
◆ bubbleSort()
void bubbleSort |
( |
int * |
arr, |
|
|
int |
size |
|
) |
| |
Bubble sort algorithm implementation.
- Parameters
-
arr | array to be sorted |
size | size of array |
44{
45 for (int i = 0; i < size - 1; i++)
46 {
47 bool swapped = false;
48
49
50 for (int j = 0; j < size - 1 - i; j++)
51 {
52 if (arr[j] > arr[j + 1])
53 {
54 swap(&arr[j], &arr[j + 1]);
55 swapped = true;
56 }
57 }
58 if (!swapped)
59 {
60
61
62 break;
63 }
64 }
65}
◆ display()
void display |
( |
const int * |
arr, |
|
|
int |
n |
|
) |
| |
Display elements of array.
- Parameters
-
arr | array to be display |
n | length of array |
18{
19 for (int i = 0; i < n; i++)
20 {
21 printf("%d ", arr[i]);
22 }
23 printf("\n");
24}
◆ main()
int main |
( |
int |
argc, |
|
|
const char * |
argv[] |
|
) |
| |
Driver Code.
90{
91
92 srand(time(NULL));
94 return 0;
95}
void test()
Test function.
Definition bubble_sort.c:70
◆ swap()
void swap |
( |
int * |
first, |
|
|
int * |
second |
|
) |
| |
Swap two values by using pointer.
- Parameters
-
first | first pointer of first number |
second | second pointer of second number |
32{
33 int temp = *first;
34 *first = *second;
35 *second = temp;
36}
◆ test()
Test function.
71{
72 const int size = 10;
73 int *arr = (
int *)
calloc(size,
sizeof(
int));
74
75
76 for (int i = 0; i < size; i++)
77 {
78 arr[i] = rand() % 100;
79 }
81 for (int i = 0; i < size - 1; ++i)
82 {
83 assert(arr[i] <= arr[i + 1]);
84 }
86}
void bubbleSort(int *arr, int size)
Bubble sort algorithm implementation.
Definition bubble_sort.c:43
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22