[libc-commits] [libc] [llvm] [libc] Improve qsort (PR #120450)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Thu Dec 19 13:13:34 PST 2024


================
@@ -19,13 +19,11 @@ LLVM_LIBC_FUNCTION(void, qsort_r,
                    (void *array, size_t array_size, size_t elem_size,
                     int (*compare)(const void *, const void *, void *),
                     void *arg)) {
-  if (array == nullptr || array_size == 0 || elem_size == 0)
-    return;
-  internal::Comparator c(compare, arg);
-  auto arr = internal::Array(reinterpret_cast<uint8_t *>(array), array_size,
-                             elem_size, c);
 
-  internal::sort(arr);
+  internal::unstable_sort(array, array_size, elem_size,
+                          [compare, arg](const void *a, const void *b) -> bool {
+                            return compare(a, b, arg) < 0;
+                          });
----------------
michaelrj-google wrote:

Looking at the code more, I understand that this is where `is_less` is defined. I still think it's not obvious to someone just reading the code, so I'd like to go with a slightly different design:
```suggestion
  internal::unstable_sort(array, array_size, elem_size,
                          [compare, arg](const void *a, const void *b) -> int {
                            return compare(a, b, arg);
                          });
```
I like the way the lambda elegantly handles the qsort vs qsort_r distinction, but for readability I'd prefer if it was consistent with the public interface. 

https://github.com/llvm/llvm-project/pull/120450


More information about the libc-commits mailing list