Skip to content
Snippets Groups Projects
Commit 6968723c authored by Jake Feddersen's avatar Jake Feddersen
Browse files

Add notes from the past few days

parent 4498016f
No related branches found
No related tags found
No related merge requests found
File added
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void insertion_sort(int *a, int n) {
int i, j, t;
for (i = 1; i < n; i++) {
for (t = a[i], j = i-1; j > -1 && a[j] > t; j--) {
a[j+1] = a[j];
}
a[j+1] = t;
}
}
/**
* data - array to sort
* n - number of items in the array
* s - size of the data items
* comparator - pointer to function to compare the data
*/
void generic_insertion_sort(void *data, int n, size_t s, int (*compare)(const void *, const void *)) {
int i, j;
void *t;
char *a;
// Not allowed to do pointer math, dereference, etc on data
// So assign the same address to a pointer we actually can work with
a = data;
t = malloc(s);
for (i = 1; i < n; i++) {
// t = a[i]
for (memcpy(t, a + (i*s), s), j = i - 1;
j > -1 && compare(a + (j*s), t) > 0;
j--) {
// a[j + 1] = a[j];
memcpy(a + ((j+1)*s), a + (j*s), s);
}
//a[j+1] = t;
memcpy(a + ((j+1) * s), t, s);
}
free(t);
}
int compare_ints(const void *v1, const void *v2) {
return *((const int *) v2) - *((const int *) v1);
}
int compare_chars(const void *v1, const void *v2) {
return *((const char *) v2) - *((const char *) v1);
}
int compare_strings(const void *v1, const void *v2) {
return strcmp(*(const char **) v1, *(const char **) v2);
}
int main(int argc, char *argv[]) {
int a[10] = {10, 93, 8, 7, 6, 25, 43, 3, 2, 1};
int i;
char c[10] = "HelloCS327";
char *s[10] = {
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten"
};
insertion_sort(a, sizeof (a) / sizeof (a[0]));
generic_insertion_sort(a, sizeof (a) / sizeof (a[0]), sizeof (a[0]), compare_ints);
for (i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
generic_insertion_sort(c, sizeof (c) / sizeof (c[0]), sizeof (c[0]), compare_chars);
for (i = 0; i < 10; i++) {
printf("%c\n", c[i]);
}
generic_insertion_sort(s, sizeof (s) / sizeof (s[0]), sizeof (s[0]), compare_strings);
for (i = 0; i < 10; i++) {
printf("%s\n", s[i]);
}
}
\ No newline at end of file
//#include <stdio.h>
#define MAX_ROOMS 20
#define min(x, y) (x < y ? x : y)
#define max(x, y) ({ \
typeof (x) _x = x; \
typeof (y) _y = y; \
_x > _y ? _x : _y; \
})
int main(int argc, char *argv[]) {
MAX_ROOMS;
min(3, 4);
min(foo(x), bar(x));
max(foo(x), bar(x));
if (10 > min(foo(x), bar(x))) {
}
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment