Skip to content

Instantly share code, notes, and snippets.

@stamaniorec
Created June 16, 2016 11:38
Show Gist options
  • Save stamaniorec/d060c4fb7fd1973c2ad349331adfd705 to your computer and use it in GitHub Desktop.
Save stamaniorec/d060c4fb7fd1973c2ad349331adfd705 to your computer and use it in GitHub Desktop.
Learning about function pointers in C by implementing bubble sort with a comparator
#include <stdio.h>
int sort_by_asc(int a, int b)
{
if(a < b) return 0;
return 1;
}
int sort_by_dsc(int a, int b)
{
if(a > b) return 0;
return 1;
}
typedef int (*comparator)(int,int);
void bubble_sort(int* arr, int length, comparator cmp)
{
int i, j;
for(i = 0; i < length - 1; ++i)
{
int flag = 1;
for(j = 0; j < length - i - 1; ++j)
{
if(cmp(arr[j], arr[j+1])) // if(arr[j] > arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
flag = 0;
}
}
printf("iteration!\n");
if(flag) break;
}
}
int main(int argc, char const *argv[])
{
int arr[] = { 3, 5, -2, 4, 4, 1 };
bubble_sort(arr, 5, sort_by_asc);
for(int i = 0; i < 5; ++i) printf("%d ", arr[i]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment