-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix small function pointer bug; add more complex test case
- Loading branch information
1 parent
af854d2
commit 7dfb47c
Showing
2 changed files
with
41 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// Test advanced practical usage of function pointers | ||
#include <source_stdlib> | ||
|
||
int ARR_LENGTH = 8; | ||
int arr[] = {2, 1, 4, 11, 23, 5, -10, -200}; | ||
|
||
// sort will sort arr using cmp | ||
// cmp is a function that returns 3 way comparison between two ints | ||
void sort(int (*cmp)(int, int)) { | ||
for (int i = 1; i < ARR_LENGTH; ++i) { | ||
int j = i; | ||
while (j > 0 && cmp(arr[j - 1], arr[j]) > 0) { | ||
int temp = arr[j]; | ||
arr[j] = arr[j - 1]; | ||
arr[j - 1] = temp; | ||
j--; | ||
} | ||
} | ||
} | ||
|
||
int asc(int a, int b) { | ||
return a - b; | ||
} | ||
|
||
int desc(int a, int b) { | ||
return b - a; | ||
} | ||
|
||
int main() { | ||
int (*cmp_arr[2])(int, int) = {asc, desc}; | ||
for (int i = 0; i < 2; i++) { | ||
sort(cmp_arr[i]); | ||
print_string("Sorted output"); | ||
for (int j = 0; j < ARR_LENGTH; ++j) { | ||
print_int(arr[j]); | ||
} | ||
print_string("End of sorted output"); | ||
} | ||
} |