diff --git a/src/array.c b/src/array.c
index 2affea7e85358ef846882a4c2590748c8277340f..0bfc1e6ff8a24a362492b8aeeb24fa7d740b90d3 100644
--- a/src/array.c
+++ b/src/array.c
@@ -1020,6 +1020,17 @@ static int obj_or_func_cmp (const struct svalue *a, const struct svalue *b)
     return -1;
 
   if (a->type == T_FUNCTION) {
+    /* Sort pike functions before builtins. */
+    if (a->subtype == FUNCTION_BUILTIN) {
+      if (b->subtype == FUNCTION_BUILTIN)
+	return a->u.efun < b->u.efun ? -1 : (a->u.efun == b->u.efun ? 0 : 1);
+      else
+	return 1;
+    }
+    else
+      if (b->subtype == FUNCTION_BUILTIN)
+	return -1;
+
     if (a->u.object->prog != b->u.object->prog)
       return a->u.object->prog < b->u.object->prog ? -1 : 1;
     if (a->subtype != b->subtype)
diff --git a/src/testsuite.in b/src/testsuite.in
index 5d20b90229ea528a7b850c896e09e7a5c60d7617..a3aebe8e006e58d4340746ef88ebc4170bf41235 100644
--- a/src/testsuite.in
+++ b/src/testsuite.in
@@ -11673,6 +11673,14 @@ test_any([[
   return -1;
 ]],-1)
 test_equal(sort (({(<2>), (<1>)})), ({(<1>), (<2>)}))
+test_any_equal([[
+  function pike_fun = lambda() {};
+  function c_fun = sleep;
+  return ({equal (sort (({pike_fun, pike_fun})), ({pike_fun, pike_fun})),
+	   equal (sort (({c_fun, c_fun})), ({c_fun, c_fun})),
+	   equal (sort (({pike_fun, c_fun})), ({pike_fun, c_fun})),
+	   equal (sort (({c_fun, pike_fun})), ({pike_fun, c_fun}))});
+]], [[({1, 1, 1, 1})]])
 
 dnl missing tests for objects, arrays, multisets and mappings