Skip to content

Instantly share code, notes, and snippets.

@AdrianSkar
Last active May 9, 2024 11:55
Show Gist options
  • Save AdrianSkar/b162390f8d8cdf656a4c0bfea8ac214b to your computer and use it in GitHub Desktop.
Save AdrianSkar/b162390f8d8cdf656a4c0bfea8ac214b to your computer and use it in GitHub Desktop.
bubble sort in C
# include <stdio.h>
// bubble sort example
void ft_sort_arr(int *arr, int size)
{
int passes = 0; // number of passes
int j; // index of the array
int temp; // temporary variable to store the value of the array
int swap_count = -1; // number of swaps in each pass, -1 to enter the loop
while (swap_count != 0)
{
swap_count = 0;
j = 0;
// print current array
while (j < size - passes - 1) // Skip sorted elems in previous passes
{ // -1 to prevent out of bound comp
if (arr[j] > arr[j + 1]) // swap if current > next
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swap_count++;
printf("Swapping %d with %d\n", arr[j], arr[j + 1]);
}
j++;
}
printf("Pass %d: \n", passes + 1);
for (int k = 0; k < size; k++) // print the array after each pass
printf("%d ", arr[k]);
printf("(%d swaps)\n", swap_count);
passes++;
}; // if no swaps made, the array is already sorted
}
int main (void)
{
int arr[] = {5,2,1,3,6,4};
int size = sizeof(arr) / sizeof(arr[0]); // arr size / size of one element
ft_sort_arr(arr, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment