Bläddra i källkod

bubble sort makro

Kajetan Johannes Hammerle 1 månad sedan
förälder
incheckning
ab6bf3cf4f
3 ändrade filer med 32 tillägg och 1 borttagningar
  1. 16 0
      include/core/Utility.h
  2. 0 1
      src/Matrix.c
  3. 16 0
      test/modules/UtilityTests.c

+ 16 - 0
include/core/Utility.h

@@ -55,4 +55,20 @@ i64 getNanos(void);
         *bPointer = tmp;                                                       \
     } while(0)
 
+#define BUBBLE_SORT(type, Type) void bubbleSort##Type(type* data, size_t n);
+#define BUBBLE_SORT_SOURCE(type, Type, greaterThan)                            \
+    void bubbleSort##Type(type* data, size_t n) {                              \
+        bool swapped = true;                                                   \
+        while(swapped && n > 0) {                                              \
+            swapped = false;                                                   \
+            n--;                                                               \
+            for(size_t i = 0; i < n; i++) {                                    \
+                if(greaterThan(data[i], data[i + 1])) {                        \
+                    swap(data + i, data + i + 1);                              \
+                    swapped = true;                                            \
+                }                                                              \
+            }                                                                  \
+        }                                                                      \
+    }
+
 #endif

+ 0 - 1
src/Matrix.c

@@ -3,7 +3,6 @@
 
 #include "core/Generic.h"
 #include "core/ToString.h"
-#include "core/Utility.h"
 
 #define M(m, x, y) ((m)->data[x].data[y])
 

+ 16 - 0
test/modules/UtilityTests.c

@@ -86,6 +86,21 @@ static void testFail() {
 #endif
 }
 
+BUBBLE_SORT(size_t, Size)
+#define greateThanSize(a, b) ((a) > (b))
+BUBBLE_SORT_SOURCE(size_t, Size, greateThanSize)
+
+static void testSort() {
+    size_t data[] = {9, 0, 3, 1, 8, 4, 6, 2, 5, 7};
+    size_t n = ARRAY_LENGTH(data);
+    bubbleSortSize(data, n);
+    bubbleSortSize(data, n);
+    bubbleSortSize(data, 0);
+    for(size_t i = 0; i < n; i++) {
+        TEST_SIZE(data[i], i);
+    }
+}
+
 void testUtility(bool light) {
     testPopCount();
     testZeroRellocate();
@@ -97,6 +112,7 @@ void testUtility(bool light) {
     testSleep(light ? 50'000'000 : 1'300'000'000);
     testSwap();
     testFail();
+    testSort();
 }
 
 static void outOfMemory(void*) {