Official Solution
#include <stdio.h>
/* Comparison function type */
typedef int (*CompareFunc)(int, int);
/* Ascending comparison */
int ascending(int a, int b) {
return a - b; // positive if a > b, negative if a < b
}
/* Descending comparison */
int descending(int a, int b) {
return b - a; // positive if b > a, negative if b < a
}
/* Generic bubble sort function */
void sort(int arr[], int n, CompareFunc cmp) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (cmp(arr[j], arr[j + 1]) > 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
/* Function to print an array */
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
}
int main() {
int arr1[] = {5, 2, 9, 1, 7};
int arr2[] = {5, 2, 9, 1, 7};
int n = 5;
printf("Original array: ");
printArray(arr1, n);
/* Sort ascending */
sort(arr1, n, ascending);
printf("Ascending sort: ");
printArray(arr1, n);
/* Sort descending */
sort(arr2, n, descending);
printf("Descending sort: ");
printArray(arr2, n);
return 0;
}
No comments yet. Start the discussion!