From patchwork Tue Oct 3 12:22:49 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Adhemerval Zanella X-Patchwork-Id: 728731 Delivered-To: patch@linaro.org Received: by 2002:a5d:60c8:0:b0:31d:da82:a3b4 with SMTP id x8csp2112789wrt; Tue, 3 Oct 2023 05:23:56 -0700 (PDT) X-Google-Smtp-Source: AGHT+IGf13mQnrZge915ll9kbyvNuze9iB8WdcZkmOJmifSltThc6BtezI65eCWOaJCMGCV41J6d X-Received: by 2002:a17:906:20ce:b0:9a1:e233:e627 with SMTP id c14-20020a17090620ce00b009a1e233e627mr14469695ejc.42.1696335835762; Tue, 03 Oct 2023 05:23:55 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1696335835; cv=none; d=google.com; s=arc-20160816; b=aCdaYWy/0lK6jXJzDOa/OkE/OKdP32bmbobAls1Q+LdbK92rXFYpjswTwyYINxhqxH nczeK4imq1DHF8PfdlQuwRvBeSyJi4mue29pPVoY96Zi9VIMM7qaDXTWqCItf3kJt31m UXYlQi3qfV7jRv/r1RDAUEaKLHj6zg/k1k3hRn14noydGBGfj804XyS8/9LA0mgw3gmm xqaoht7XqKOi+hUW/VmACMD7ynjXHTv6wHETNkmKrGWmKAg4ifahsZJQ9niGYrkJWbL9 ilflSv6UorkGBOebYRxuaMhzmPHoEo+ZxJPtp6G5BfTnIcNGo3+b3vie2HrQya+3aS8i i2+g== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=errors-to:list-subscribe:list-help:list-post:list-archive :list-unsubscribe:list-id:precedence:content-transfer-encoding :mime-version:references:in-reply-to:message-id:date:subject:to:from :dkim-signature:dmarc-filter:delivered-to; bh=9m8Ahb3Yj9ux4Gp/JQXWajleurIMjvebrE9EcJ39dr0=; fh=ubzLPtaquqORyAJ/TX35zypB35/iXKzZJOEWlgP8mu4=; b=BDQVJAh21Ofe4vn29pDcGHvVwjtABp8qSpHYTaEKt/h0GbGb13KmrnTX68Kd7RmqaV egwmjg+N586bnkhdZq3gPkgXClt6djmNj8a5DetbZln8MCOGxrxTsQmu9dw3so3nnShb 5nvj0xo0mUcSeF6rjM/m1D1muCBJ3MgeiM0vfZpc+VnYK0L9SvGewRtsa845JMbK+HBA /iiw0q12TTnrkdGRRgJq8ZDkbu1E/8SEKWVXp/Hunuv0plQ4sG2dORp+ldD60a64nccu 9ILXI7r2MTUf8ZaUnws2MuffGzkeTec9LO5N5x1zxEzQZBF5snmYwIjhdaSNcKydGlXu bomg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@linaro.org header.s=google header.b=Aole4Elh; spf=pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 2620:52:3:1:0:246e:9693:128c as permitted sender) smtp.mailfrom="libc-alpha-bounces+patch=linaro.org@sourceware.org"; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=linaro.org Return-Path: Received: from server2.sourceware.org (server2.sourceware.org. [2620:52:3:1:0:246e:9693:128c]) by mx.google.com with ESMTPS id a14-20020a1709062b0e00b009a19ccdeae6si657988ejg.358.2023.10.03.05.23.55 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 03 Oct 2023 05:23:55 -0700 (PDT) Received-SPF: pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 2620:52:3:1:0:246e:9693:128c as permitted sender) client-ip=2620:52:3:1:0:246e:9693:128c; Authentication-Results: mx.google.com; dkim=pass header.i=@linaro.org header.s=google header.b=Aole4Elh; spf=pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 2620:52:3:1:0:246e:9693:128c as permitted sender) smtp.mailfrom="libc-alpha-bounces+patch=linaro.org@sourceware.org"; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=linaro.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 8A3B73875434 for ; Tue, 3 Oct 2023 12:23:54 +0000 (GMT) X-Original-To: libc-alpha@sourceware.org Delivered-To: libc-alpha@sourceware.org Received: from mail-pl1-x631.google.com (mail-pl1-x631.google.com [IPv6:2607:f8b0:4864:20::631]) by sourceware.org (Postfix) with ESMTPS id 084983858C33 for ; Tue, 3 Oct 2023 12:23:08 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 084983858C33 Authentication-Results: sourceware.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=linaro.org Received: by mail-pl1-x631.google.com with SMTP id d9443c01a7336-1bf55a81eeaso6430265ad.0 for ; Tue, 03 Oct 2023 05:23:07 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1696335786; x=1696940586; darn=sourceware.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to; bh=9m8Ahb3Yj9ux4Gp/JQXWajleurIMjvebrE9EcJ39dr0=; b=Aole4ElhFdJbe9vNDWbIEKgL6XO+u+mTRY4g0UafLm5kfYkpC7dQFu88jFe1BwTItA rlgl+ldtsyBjnkfpLMOzAJ4wODq3UPN6D1Gvxu53Qt78m+8OrnYTPUH8jKcJL6h7aqxH ezvTHRFIFsbFDmBwzSnmIwUutbT6wjivnw8ADtVpZwFgI788fneRh7/msq1dCziELq7f KC4pCYJYcICO3OZGXrkhuxT+Zr2W0KFJVcbdY2VWNFywe2syk9h8bmrztfwcFL+GDXwb FIlllQiEV8LmZrawAe/IDrWubxdmlOnxSKu1BIf+0wu+JU5w0phs+BjOJEx/KkDW8iaL N47g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696335786; x=1696940586; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=9m8Ahb3Yj9ux4Gp/JQXWajleurIMjvebrE9EcJ39dr0=; b=toEk00+utmyGxmQYzzJ63PxqOLgOBAVtxt1o8b22YeTKPvjB2Abzxudz7vsM+bqOE3 Dk8ffI6cI5KCgSfWVqJki5bgrJ2tgO/CYdqoa07wxlPEu85av50lUcD6I4vJOfZsbFu8 stwsepLWWm1bEpbNdSASIQFju+JHDBGY3KsNLI36W9lq/ZBHy4lIkh+p0ym5LCbG0Dq1 hA4KRm4Qm+8ss6vUussPgkhDDGDuYOMibxxanDnQPOfQhHJ/S3SR0CXjh0Tam2XKklW0 eajTalI2JPTGgLLBy9kKZo035KqTQHUa6KM0Z/h5LJ3Q4v6PXCHhF8vshW8eGTn+6JyU 0aGA== X-Gm-Message-State: AOJu0YwihRuIZvT4e4zH4CwWPHOPFI7V8iPO6mnQdqEyaQ02eFPPWGS9 SqBlRvhztNxQV1MBVZMLqIWHsoewoVkUw29S05QXIw== X-Received: by 2002:a17:902:a983:b0:1c7:3002:6ba3 with SMTP id bh3-20020a170902a98300b001c730026ba3mr11439399plb.8.1696335786426; Tue, 03 Oct 2023 05:23:06 -0700 (PDT) Received: from mandiga.. ([2804:1b3:a7c1:feaf:31ef:b40c:b4e5:77c]) by smtp.gmail.com with ESMTPSA id b1-20020a170902d30100b001c5de2f1686sm1403881plc.99.2023.10.03.05.23.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 03 Oct 2023 05:23:05 -0700 (PDT) From: Adhemerval Zanella To: libc-alpha@sourceware.org, Noah Goldstein , Paul Eggert , Florian Weimer Subject: [PATCH v8 5/7] stdlib: Implement introsort for qsort (BZ 19305) Date: Tue, 3 Oct 2023 09:22:49 -0300 Message-Id: <20231003122251.3325435-6-adhemerval.zanella@linaro.org> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20231003122251.3325435-1-adhemerval.zanella@linaro.org> References: <20231003122251.3325435-1-adhemerval.zanella@linaro.org> MIME-Version: 1.0 X-Spam-Status: No, score=-12.6 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: libc-alpha@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Libc-alpha mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libc-alpha-bounces+patch=linaro.org@sourceware.org This patch makes the quicksort implementation to acts as introsort, to avoid worse-case performance (and thus making it O(nlog n)). It switch to heapsort when the depth level reaches 2*log2(total elements). The heapsort is a textbook implementation. Checked on x86_64-linux-gnu and aarch64-linux-gnu. Reviewed-by: Noah Goldstein --- stdlib/qsort.c | 89 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/stdlib/qsort.c b/stdlib/qsort.c index 80706b3357..d5f205affc 100644 --- a/stdlib/qsort.c +++ b/stdlib/qsort.c @@ -98,6 +98,7 @@ typedef struct { char *lo; char *hi; + size_t depth; } stack_node; /* The stack needs log (total_elements) entries (we could even subtract @@ -107,22 +108,85 @@ typedef struct enum { STACK_SIZE = CHAR_BIT * sizeof (size_t) }; static inline stack_node * -push (stack_node *top, char *lo, char *hi) +push (stack_node *top, char *lo, char *hi, size_t depth) { top->lo = lo; top->hi = hi; + top->depth = depth; return ++top; } static inline stack_node * -pop (stack_node *top, char **lo, char **hi) +pop (stack_node *top, char **lo, char **hi, size_t *depth) { --top; *lo = top->lo; *hi = top->hi; + *depth = top->depth; return top; } +/* NB: N is inclusive bound for BASE. */ +static inline void +siftdown (void *base, size_t size, size_t k, size_t n, + enum swap_type_t swap_type, __compar_d_fn_t cmp, void *arg) +{ + while (k <= n / 2) + { + size_t j = 2 * k; + if (j < n && cmp (base + (j * size), base + ((j + 1) * size), arg) < 0) + j++; + + if (cmp (base + (k * size), base + (j * size), arg) >= 0) + break; + + do_swap (base + (size * j), base + (k * size), size, swap_type); + k = j; + } +} + +static inline void +heapify (void *base, size_t size, size_t n, enum swap_type_t swap_type, + __compar_d_fn_t cmp, void *arg) +{ + size_t k = n / 2; + while (1) + { + siftdown (base, size, k, n, swap_type, cmp, arg); + if (k-- == 0) + break; + } +} + +/* A non-recursive heapsort, used on introsort implementation as a fallback + routine with worst-case performance of O(nlog n) and worst-case space + complexity of O(1). It sorts the array starting at BASE and ending at + END, with each element of SIZE bytes. The SWAP_TYPE is the callback + function used to swap elements, and CMP is the function used to compare + elements. */ +static void +heapsort_r (void *base, void *end, size_t size, enum swap_type_t swap_type, + __compar_d_fn_t cmp, void *arg) +{ + const size_t count = ((uintptr_t) end - (uintptr_t) base) / size; + + if (count < 2) + return; + + size_t n = count - 1; + + /* Build the binary heap, largest value at the base[0]. */ + heapify (base, size, n, swap_type, cmp, arg); + + /* On each iteration base[0:n] is the binary heap, while base[n:count] + is sorted. */ + while (n > 0) + { + do_swap (base, base + (n * size), size, swap_type); + n--; + siftdown (base, size, 0, n, swap_type, cmp, arg); + } +} static inline void insertion_sort_qsort_partitions (void *const pbase, size_t total_elems, @@ -208,7 +272,7 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, const size_t max_thresh = MAX_THRESH * size; - if (total_elems == 0) + if (total_elems <= 1) /* Avoid lossage with unsigned arithmetic below. */ return; @@ -220,15 +284,26 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, else swap_type = SWAP_BYTES; + /* Maximum depth before quicksort switches to heapsort. */ + size_t depth = 2 * (sizeof (size_t) * CHAR_BIT - 1 + - __builtin_clzl (total_elems)); + if (total_elems > MAX_THRESH) { char *lo = base_ptr; char *hi = &lo[size * (total_elems - 1)]; stack_node stack[STACK_SIZE]; - stack_node *top = stack + 1; + stack_node *top = push (stack, NULL, NULL, depth); while (stack < top) { + if (depth == 0) + { + heapsort_r (lo, hi, size, swap_type, cmp, arg); + top = pop (top, &lo, &hi, &depth); + continue; + } + char *left_ptr; char *right_ptr; @@ -292,7 +367,7 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, { if ((size_t) (hi - left_ptr) <= max_thresh) /* Ignore both small partitions. */ - top = pop (top, &lo, &hi); + top = pop (top, &lo, &hi, &depth); else /* Ignore small left partition. */ lo = left_ptr; @@ -303,13 +378,13 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, else if ((right_ptr - lo) > (hi - left_ptr)) { /* Push larger left partition indices. */ - top = push (top, lo, right_ptr); + top = push (top, lo, right_ptr, depth - 1); lo = left_ptr; } else { /* Push larger right partition indices. */ - top = push (top, left_ptr, hi); + top = push (top, left_ptr, hi, depth - 1); hi = right_ptr; } }