commit ead3cc26dcfa67a82e66d190a0696838efcaa063
parent 97089615314bbf37377e8a1bd02dd591fbdf8c4d
Author: bsandro <brian.drosan@gmail.com>
Date: Sun, 19 Dec 2021 18:02:59 +0200
Day 07 stdlib qsort instead of my potato one
Diffstat:
3 files changed, 10 insertions(+), 34 deletions(-)
diff --git a/common/quicksort.h b/common/quicksort.h
@@ -1,30 +0,0 @@
-#pragma once
-
-/* ******************* quicksort ***********************/
-
-static void qs_swap(long long *a, long long *b) {
- long long tmp = *a;
- *a = *b;
- *b = tmp;
-}
-
-static long long qs_partition(long long *numbers, long long low, long long high) {
- long long pivot = numbers[high];
- long long i = low - 1;
- for (long long j = low; j <= high - 1; ++j) {
- if (numbers[j] < pivot) {
- i++;
- qs_swap(&numbers[i], &numbers[j]);
- }
- }
- qs_swap(&numbers[i+1], &numbers[high]);
- return i + 1;
-}
-
-static void qs(long long *numbers, long long low, long long high) {
- if (low < high) {
- long long p = qs_partition(numbers, low, high);
- qs(numbers, low, p - 1);
- qs(numbers, p + 1, high);
- }
-}
diff --git a/day07/puzzle.c b/day07/puzzle.c
@@ -11,10 +11,13 @@
#include <math.h>
#include "util.h"
-#include "quicksort.h"
#define STR_LEN 16384
+static int compare(const void *l, const void *r) {
+ return *(long long *)l - *(long long *)r;
+}
+
void puzzle(const char *filename, size_t *result1, size_t *result2) {
FILE *infile = fopen(filename, "r");
if (infile == NULL) {
@@ -34,7 +37,7 @@ void puzzle(const char *filename, size_t *result1, size_t *result2) {
bzero(buf, STR_LEN);
}
- qs((long long *)numbers.data, 0, numbers.count - 1);
+ qsort(numbers.data, numbers.count, numbers.elem_size, compare);
// median average
size_t index = numbers.count / 2;
diff --git a/day07/puzzle_brute.c b/day07/puzzle_brute.c
@@ -12,10 +12,13 @@
#include <limits.h>
#include "util.h"
-#include "quicksort.h"
#define STR_LEN 16384
+static int compare(const void *l, const void *r) {
+ return *(long long *)l - *(long long *)r;
+}
+
void puzzle_brute(const char *filename, size_t *result1, size_t *result2) {
FILE *infile = fopen(filename, "r");
if (infile == NULL) {
@@ -35,7 +38,7 @@ void puzzle_brute(const char *filename, size_t *result1, size_t *result2) {
bzero(buf, STR_LEN);
}
- qs((long long *)numbers.data, 0, numbers.count - 1);
+ qsort(numbers.data, numbers.count, numbers.elem_size, compare);
// median average
size_t index = numbers.count / 2;