Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Last active May 27, 2022 03:42
Show Gist options
  • Save Per48edjes/e103e87129ebf9ddd73d384dcd758bbd to your computer and use it in GitHub Desktop.
Save Per48edjes/e103e87129ebf9ddd73d384dcd758bbd to your computer and use it in GitHub Desktop.
Implementation of bubble sort on array of integers in C
#include <stdio.h>
void swap(int *a, int *b);
void print_array(int *arr, int len_arr);
int main(void)
{
int items[] = { 5, 2, 7, 4, 1, 6, 3, 0 };
int len_items = sizeof(items) / sizeof(*items);
// Print original order
print_array(items, len_items);
// Bubble sort
int swaps_count;
int j = len_items - 1;
do
{
swaps_count = 0;
for (int i = 0; i < j; ++i)
{
if (items[i] > items[i + 1])
{
swap(&items[i], &items[i + 1]);
swaps_count += 1;
}
}
--j;
} while (swaps_count > 0);
// Print sorted order
print_array(items, len_items);
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void print_array(int *arr, int len_arr)
{
for (int i = 0; i < len_arr; ++i)
{
printf("%d ", arr[i]);
if (len_arr - 1 == i)
{
printf("\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment