diff --git a/src/space.c b/src/space.c
index 2f53223a67b48cc17ba0c8776cd6b070160de047..a95548992d899c24e733e59b96c6ec1972feaa5c 100644
--- a/src/space.c
+++ b/src/space.c
@@ -49,6 +49,7 @@
 #include "hydro.h"
 #include "kernel_hydro.h"
 #include "lock.h"
+#include "memswap.h"
 #include "minmax.h"
 #include "runner.h"
 #include "threadpool.h"
@@ -1043,15 +1044,9 @@ void space_parts_sort_mapper(void *map_data, int num_elements,
         while (ii <= j && ind[ii] <= pivot) ii++;
         while (jj >= i && ind[jj] > pivot) jj--;
         if (ii < jj) {
-          size_t temp_i = ind[ii];
-          ind[ii] = ind[jj];
-          ind[jj] = temp_i;
-          struct part temp_p = parts[ii];
-          parts[ii] = parts[jj];
-          parts[jj] = temp_p;
-          struct xpart temp_xp = xparts[ii];
-          xparts[ii] = xparts[jj];
-          xparts[jj] = temp_xp;
+          memswap(&ind[ii], &ind[jj], sizeof(size_t));
+          memswap(&parts[ii], &parts[jj], sizeof(struct part));
+          memswap(&xparts[ii], &xparts[jj], sizeof(struct xpart));
         }
       }
 
@@ -1226,12 +1221,8 @@ void space_gparts_sort_mapper(void *map_data, int num_elements,
         while (ii <= j && ind[ii] <= pivot) ii++;
         while (jj >= i && ind[jj] > pivot) jj--;
         if (ii < jj) {
-          size_t temp_i = ind[ii];
-          ind[ii] = ind[jj];
-          ind[jj] = temp_i;
-          struct gpart temp_p = gparts[ii];
-          gparts[ii] = gparts[jj];
-          gparts[jj] = temp_p;
+          memswap(&ind[ii], &ind[jj], sizeof(size_t));
+          memswap(&gparts[ii], &gparts[jj], sizeof(size_t));
         }
       }