Skip to content

Instantly share code, notes, and snippets.

@flisboac
Last active September 8, 2015 15:20
Show Gist options
  • Save flisboac/abcdb9e7549c82fe655c to your computer and use it in GitHub Desktop.
Save flisboac/abcdb9e7549c82fe655c to your computer and use it in GitHub Desktop.
Sorts and prints the integer set passed as program arguments.
Sorts and prints the integer set passed as program arguments.
#include <stdio.h>
#include <stdlib.h>
static int compare_ints(const void* a, const void* b);
static int *new_int_array(size_t sz);
static void sort_int_array(int *array, size_t sz);
static void print_int_array(const int *array, size_t sz, FILE *file);
static void delete_int_array(int *array, size_t sz);
int main(int argc, char** argv) {
int i, *array;
size_t nelems = argc - 1;
if (argc <= 1) {
fprintf(stderr, "Please inform the numbers to be sorted.\n");
exit(1);
}
array = new_int_array(nelems);
for (i = 0; i < nelems; ++i) {
array[i] = atoi(argv[i + 1]);
}
sort_int_array(array, nelems);
print_int_array(array, nelems, stdout);
delete_int_array(array, nelems);
return 0;
}
int compare_ints(const void* a, const void* b) {
int va = *((int*) a);
int vb = *((int*) b);
return (va - vb) - (vb - va);
}
int *new_int_array(size_t sz) {
int *array = calloc(sz, sizeof(int));
if (!array) {
fprintf(stderr, "Could not allocate array for %d ints. Exiting...\n", sz);
exit(1);
}
return array;
}
void sort_int_array(int *array, size_t sz) {
qsort(array, sz, sizeof(int), compare_ints);
}
void print_int_array(const int *array, size_t sz, FILE *file) {
const char* sep = "";
fprintf(file, "[");
int i;
for (i = 0; i < sz; ++i) {
fprintf(file, "%s%d", sep, *(array + i));
sep = ", ";
}
fprintf(file, "]");
}
void delete_int_array(int *array, size_t sz) {
free(array);
}
CC=gcc -c -o
PROG=gcc -o
RM=rm -f
CFLAGS=-Wall
LIBS=
PROGRAM=intsort.exe
OBJS=intsort.o
all: $(PROGRAM)
clean:
$(RM) $(PROGRAM) $(OBJS)
$(PROGRAM): $(OBJS)
$(PROG) $@ $? $(LIBS)
.c.o:
$(CC) $@ $? $(CFLAGS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment