Content-Length: 354446 | pFad | http://github.com/postgrespro/postgres/commit/40b0c10b763dfe4d6b171a58a2bd49cc3f880087

3F Replace insertion sort in contrib/intarray with qsort(). · postgrespro/postgres@40b0c10 · GitHub
Skip to content

Commit 40b0c10

Browse files
committed
Replace insertion sort in contrib/intarray with qsort().
It's all very well to claim that a simplistic sort is fast in easy cases, but O(N^2) in the worst case is not good ... especially if the worst case is as easy to hit as "descending order input". Replace that bit with our standard qsort. Per bug #12866 from Maksym Boguk. Back-patch to all active branches.
1 parent 396ef6f commit 40b0c10

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

contrib/intarray/_int_tool.c

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -195,39 +195,38 @@ rt__int_size(ArrayType *a, float *size)
195195
return;
196196
}
197197

198+
/* qsort_arg comparison function for isort() */
199+
static int
200+
isort_cmp(const void *a, const void *b, void *arg)
201+
{
202+
int4 aval = *((const int4 *) a);
203+
int4 bval = *((const int4 *) b);
204+
205+
if (aval < bval)
206+
return -1;
207+
if (aval > bval)
208+
return 1;
209+
210+
/*
211+
* Report if we have any duplicates. If there are equal keys, qsort must
212+
* compare them at some point, else it wouldn't know whether one should go
213+
* before or after the other.
214+
*/
215+
*((bool *) arg) = true;
216+
return 0;
217+
}
198218

199-
/* len >= 2 */
219+
/* Sort the given data (len >= 2). Return true if any duplicates found */
200220
bool
201221
isort(int4 *a, int len)
202222
{
203-
int4 tmp,
204-
index;
205-
int4 *cur,
206-
*end;
207-
bool r = FALSE;
208-
209-
end = a + len;
210-
do
211-
{
212-
index = 0;
213-
cur = a + 1;
214-
while (cur < end)
215-
{
216-
if (*(cur - 1) > *cur)
217-
{
218-
tmp = *(cur - 1);
219-
*(cur - 1) = *cur;
220-
*cur = tmp;
221-
index = 1;
222-
}
223-
else if (!r && *(cur - 1) == *cur)
224-
r = TRUE;
225-
cur++;
226-
}
227-
} while (index);
223+
bool r = false;
224+
225+
qsort_arg(a, len, sizeof(int4), isort_cmp, (void *) &r);
228226
return r;
229227
}
230228

229+
/* Create a new int array with room for "num" elements */
231230
ArrayType *
232231
new_intArrayType(int num)
233232
{

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/postgrespro/postgres/commit/40b0c10b763dfe4d6b171a58a2bd49cc3f880087

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy