diff --git c/Makefile.am w/Makefile.am
index f82cefa..18fd709 100644
--- c/Makefile.am
+++ w/Makefile.am
@@ -40,7 +40,7 @@ libxml2_la_SOURCES = SAX.c entities.c encoding.c error.c parserInternals.c  \
 		xmlregexp.c xmlschemas.c xmlschemastypes.c xmlunicode.c \
 		triostr.c trio.c xmlreader.c relaxng.c dict.c SAX2.c \
 		xmlwriter.c legacy.c chvalid.c pattern.c xmlsave.c \
-		xmlmodule.c schematron.c xzlib.c
+		xmlmodule.c schematron.c xzlib.c sort.c
 else
 libxml2_la_SOURCES = SAX.c entities.c encoding.c error.c parserInternals.c  \
 		parser.c tree.c hash.c list.c xmlIO.c xmlmemory.c uri.c  \
@@ -50,7 +50,7 @@ libxml2_la_SOURCES = SAX.c entities.c encoding.c error.c parserInternals.c  \
 		xmlregexp.c xmlschemas.c xmlschemastypes.c xmlunicode.c \
 		xmlreader.c relaxng.c dict.c SAX2.c \
 		xmlwriter.c legacy.c chvalid.c pattern.c xmlsave.c \
-		xmlmodule.c schematron.c xzlib.c
+		xmlmodule.c schematron.c xzlib.c sort.c
 endif
 
 DEPS = $(top_builddir)/libxml2.la
diff --git c/Makefile.in w/Makefile.in
index 6e88cc9..6b079e6 100644
--- c/Makefile.in
+++ w/Makefile.in
@@ -103,7 +103,7 @@ am__libxml2_la_SOURCES_DIST = SAX.c entities.c encoding.c error.c \
 	xmlregexp.c xmlschemas.c xmlschemastypes.c xmlunicode.c \
 	xmlreader.c relaxng.c dict.c SAX2.c xmlwriter.c legacy.c \
 	chvalid.c pattern.c xmlsave.c xmlmodule.c schematron.c xzlib.c \
-	triostr.c trio.c
+	triostr.c trio.c sort.c
 @WITH_TRIO_SOURCES_FALSE@am_libxml2_la_OBJECTS = SAX.lo entities.lo \
 @WITH_TRIO_SOURCES_FALSE@	encoding.lo error.lo \
 @WITH_TRIO_SOURCES_FALSE@	parserInternals.lo parser.lo tree.lo \
@@ -607,7 +607,7 @@ libxml2_la_LDFLAGS = @CYGWIN_EXTRA_LDFLAGS@ @WIN32_EXTRA_LDFLAGS@ \
 @WITH_TRIO_SOURCES_FALSE@		xmlregexp.c xmlschemas.c xmlschemastypes.c xmlunicode.c \
 @WITH_TRIO_SOURCES_FALSE@		xmlreader.c relaxng.c dict.c SAX2.c \
 @WITH_TRIO_SOURCES_FALSE@		xmlwriter.c legacy.c chvalid.c pattern.c xmlsave.c \
-@WITH_TRIO_SOURCES_FALSE@		xmlmodule.c schematron.c xzlib.c
+@WITH_TRIO_SOURCES_FALSE@		xmlmodule.c schematron.c xzlib.c sort.c
 
 @WITH_TRIO_SOURCES_TRUE@libxml2_la_SOURCES = SAX.c entities.c encoding.c error.c parserInternals.c  \
 @WITH_TRIO_SOURCES_TRUE@		parser.c tree.c hash.c list.c xmlIO.c xmlmemory.c uri.c  \
@@ -617,7 +617,7 @@ libxml2_la_LDFLAGS = @CYGWIN_EXTRA_LDFLAGS@ @WIN32_EXTRA_LDFLAGS@ \
 @WITH_TRIO_SOURCES_TRUE@		xmlregexp.c xmlschemas.c xmlschemastypes.c xmlunicode.c \
 @WITH_TRIO_SOURCES_TRUE@		triostr.c trio.c xmlreader.c relaxng.c dict.c SAX2.c \
 @WITH_TRIO_SOURCES_TRUE@		xmlwriter.c legacy.c chvalid.c pattern.c xmlsave.c \
-@WITH_TRIO_SOURCES_TRUE@		xmlmodule.c schematron.c xzlib.c
+@WITH_TRIO_SOURCES_TRUE@		xmlmodule.c schematron.c xzlib.c sort.c
 
 DEPS = $(top_builddir)/libxml2.la
 LDADDS = @STATIC_BINARIES@ $(top_builddir)/libxml2.la @THREAD_LIBS@ @Z_LIBS@ @LZMA_LIBS@ $(ICONV_LIBS) @M_LIBS@ @WIN32_EXTRA_LIBADD@
diff --git c/include/libxml/xpath.h w/include/libxml/xpath.h
index ddd9dd8..f28ff8d 100644
--- c/include/libxml/xpath.h
+++ w/include/libxml/xpath.h
@@ -267,6 +267,17 @@ typedef xmlXPathFunction (*xmlXPathFuncLookupFunc) (void *ctxt,
  */
 #define XML_XPATH_NOVAR	  (1<<1)
 
+/*
+* XP_OPTIMIZED_NON_ELEM_COMPARISON:
+* If defined, this will use xmlXPathCmpNodesExt() instead of
+* xmlXPathCmpNodes(). The new function is optimized comparison of
+* non-element nodes; actually it will speed up comparison only if
+* xmlXPathOrderDocElems() was called in order to index the elements of
+* a tree in document order; Libxslt does such an indexing, thus it will
+* benefit from this optimization.
+*/
+#define XP_OPTIMIZED_NON_ELEM_COMPARISON
+
 /**
  * xmlXPathContext:
  *
@@ -449,6 +460,12 @@ XMLPUBFUN xmlXPathObjectPtr XMLCALL
 XMLPUBFUN int XMLCALL		   
 		    xmlXPathCmpNodes		(xmlNodePtr node1,
 						 xmlNodePtr node2);
+#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCmpNodesExt		(xmlNodePtr node1,
+						 xmlNodePtr node2);
+#endif /* XP_OPTIMIZED_NON_ELEM_COMPARISON */
+
 /**
  * Conversion functions to basic types.
  */
diff --git c/include/libxml/xpathInternals.h w/include/libxml/xpathInternals.h
index dcd5243..f0e3a0f 100644
--- c/include/libxml/xpathInternals.h
+++ w/include/libxml/xpathInternals.h
@@ -510,6 +510,9 @@ XMLPUBFUN void XMLCALL
 						 xmlNsPtr ns);
 XMLPUBFUN void XMLCALL              
 		xmlXPathNodeSetSort		(xmlNodeSetPtr set);
+XMLPUBFUN void XMLCALL              
+		xmlNodeTimSort		(xmlNodePtr *dst,
+						 const size_t size);
 
 XMLPUBFUN void XMLCALL		  
 		xmlXPathRoot			(xmlXPathParserContextPtr ctxt);
diff --git c/sort.c w/sort.c
new file mode 100644
index 0000000..9100b10
--- /dev/null
+++ w/sort.c
@@ -0,0 +1,519 @@
+/*
+ * Based on https://github.com/swenson/sort
+ */
+
+/*
+All code in this repository, unless otherwise specified, is hereby licensed under the MIT Public License:
+Copyright (c) 2010 Christopher Swenson
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+#define IN_LIBXML
+#include "libxml.h"
+
+#include <string.h>
+#include <stdint.h>
+
+#include <libxml/xpath.h>
+
+/*
+ * Here we define macros that instantiate the generic sorting functions
+ * for our case: sorting xmlNodePtrs.
+ * This code was originally in a header file, but since we need only one
+ * specific sorting function, it was put in a .c file.
+ */
+#define SORT_NAME xmlNode
+#define SORT_TYPE xmlNodePtr
+int xmlWrapCmp( xmlNodePtr x, xmlNodePtr y );
+#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
+    int xmlWrapCmp( xmlNodePtr x, xmlNodePtr y )
+    {
+        int res = xmlXPathCmpNodesExt(x, y);
+        return res == -2 ? res : -res;
+    }
+#else
+    int xmlWrapCmp( xmlNodePtr x, xmlNodePtr y )
+    {
+        int res = xmlXPathCmpNodes(x, y);
+        return res == -2 ? res : -res;
+    }
+#endif
+#define SORT_CMP(x, y)  (xmlWrapCmp(x, y))
+
+#ifndef MAX
+#define MAX(x,y) (((x) > (y) ? (x) : (y)))
+#endif
+#ifndef MIN
+#define MIN(x,y) (((x) < (y) ? (x) : (y)))
+#endif
+
+int compute_minrun(const uint64_t);
+
+#ifndef CLZ
+#ifdef __GNUC__
+#define CLZ __builtin_clzll
+#else
+
+int clzll(uint64_t);
+
+/* adapted from Hacker's Delight */
+int clzll(uint64_t x) /* {{{ */
+{
+  int n;
+
+  if (x == 0) return(64);
+  n = 0;
+  if (x <= 0x00000000FFFFFFFFL) {n = n + 32; x = x << 32;}
+  if (x <= 0x0000FFFFFFFFFFFFL) {n = n + 16; x = x << 16;}
+  if (x <= 0x00FFFFFFFFFFFFFFL) {n = n + 8; x = x << 8;}
+  if (x <= 0x0FFFFFFFFFFFFFFFL) {n = n + 4; x = x << 4;}
+  if (x <= 0x3FFFFFFFFFFFFFFFL) {n = n + 2; x = x << 2;}
+  if (x <= 0x7FFFFFFFFFFFFFFFL) {n = n + 1;}
+  return n;
+}
+/* }}} */
+
+#define CLZ clzll
+#endif
+#endif
+
+int compute_minrun(const uint64_t size) /* {{{ */
+{
+  const int top_bit = 64 - CLZ(size);
+  const int shift = MAX(top_bit, 6) - 6;
+  const int minrun = size >> shift;
+  const uint64_t mask = (1ULL << shift) - 1;
+  if (mask & size) return minrun + 1;
+  return minrun;
+}
+/* }}} */
+
+#ifndef SORT_NAME
+#error "Must declare SORT_NAME"
+#endif
+
+#ifndef SORT_TYPE
+#error "Must declare SORT_TYPE"
+#endif
+
+#ifndef SORT_CMP
+#define SORT_CMP(x, y)  ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1))
+#endif
+
+
+#define SORT_SWAP(x,y) {SORT_TYPE __SORT_SWAP_t = (x); (x) = (y); (y) = __SORT_SWAP_t;}
+
+#define SORT_CONCAT(x, y) x ## _ ## y
+#define SORT_MAKE_STR1(x, y) SORT_CONCAT(x,y)
+#define SORT_MAKE_STR(x) SORT_MAKE_STR1(SORT_NAME,x)
+
+#define BINARY_INSERTION_FIND  SORT_MAKE_STR(BinaryInsertionFind)
+#define BINARY_INSERTION_SORT_START SORT_MAKE_STR(BinaryInsertionSortStart)
+#define BINARY_INSERTION_SORT  SORT_MAKE_STR(BinaryInsertionSort)
+#define REVERSE_ELEMENTS       SORT_MAKE_STR(ReverseElements)
+#define COUNT_RUN              SORT_MAKE_STR(CountRun)
+#define CHECK_INVARIANT        SORT_MAKE_STR(CheckInvariant)
+#define TIM_SORT               SORT_MAKE_STR(TimSort)
+#define TIM_SORT_RESIZE        SORT_MAKE_STR(TimSortResize)
+#define TIM_SORT_MERGE         SORT_MAKE_STR(TimSortMerge)
+#define TIM_SORT_COLLAPSE      SORT_MAKE_STR(TimSortCollapse)
+
+#define TIM_SORT_RUN_T         SORT_MAKE_STR(TimSortRun)
+#define TEMP_STORAGE_T         SORT_MAKE_STR(TempStorage)
+
+typedef struct {
+  int64_t start;
+  int64_t length;  
+} TIM_SORT_RUN_T;
+
+void BINARY_INSERTION_SORT(SORT_TYPE *dst, const size_t size);
+void TIM_SORT(SORT_TYPE *dst, const size_t size);
+
+/* Function used to do a binary search for binary insertion sort */
+static int64_t BINARY_INSERTION_FIND(SORT_TYPE *dst, const SORT_TYPE x, const size_t size)
+{
+  int64_t l, c, r;
+  SORT_TYPE lx;
+  SORT_TYPE cx;
+  l = 0;
+  r = size - 1;
+  c = r >> 1;
+  lx = dst[l];
+  
+  /* check for beginning conditions */
+  if (SORT_CMP(x, lx) < 0)
+    return 0;
+  else if (SORT_CMP(x, lx) == 0)
+  {
+    int64_t i = 1;
+    while (SORT_CMP(x, dst[i]) == 0) i++;
+    return i;
+  }
+  
+  cx = dst[c];
+  while (1)
+  {
+    const int val = SORT_CMP(x, cx);
+    if (val < 0)
+    {
+      if (c - l <= 1) return c;
+      r = c;
+    }
+    else if (val > 0)
+    {
+      if (r - c <= 1) return c + 1;
+      l = c;
+      lx = cx;
+    }
+    else
+    {
+      do
+      {
+        cx = dst[++c];
+      } while (SORT_CMP(x, cx) == 0);
+      return c;
+    }
+    c = l + ((r - l) >> 1);
+    cx = dst[c];
+  }
+}
+
+/* Binary insertion sort, but knowing that the first "start" entries are sorted.  Used in timsort. */
+static void BINARY_INSERTION_SORT_START(SORT_TYPE *dst, const size_t start, const size_t size)
+{
+  int64_t i;
+  for (i = start; i < size; i++)
+  {
+    int64_t j;
+    SORT_TYPE x;
+    int64_t location;
+    /* If this entry is already correct, just move along */
+    if (SORT_CMP(dst[i - 1], dst[i]) <= 0) continue;
+    
+    /* Else we need to find the right place, shift everything over, and squeeze in */
+    x = dst[i];
+    location = BINARY_INSERTION_FIND(dst, x, i);
+    for (j = i - 1; j >= location; j--)
+    {
+      dst[j + 1] = dst[j];
+    }
+    dst[location] = x;
+  }
+}
+
+/* Binary insertion sort */
+void BINARY_INSERTION_SORT(SORT_TYPE *dst, const size_t size)
+{
+  BINARY_INSERTION_SORT_START(dst, 1, size);
+}
+
+/* timsort implementation, based on timsort.txt */
+
+static void REVERSE_ELEMENTS(SORT_TYPE *dst, int64_t start, int64_t end)
+{
+  while (1)
+  {
+    if (start >= end) return;
+    SORT_SWAP(dst[start], dst[end]);
+    start++;
+    end--;
+  }
+}
+
+static int64_t COUNT_RUN(SORT_TYPE *dst, const int64_t start, const size_t size)
+{
+	int64_t curr;
+  if (size - start == 1) return 1;
+  if (start >= size - 2)
+  {
+    if (SORT_CMP(dst[size - 2], dst[size - 1]) > 0)
+      SORT_SWAP(dst[size - 2], dst[size - 1]);
+    return 2;
+  }
+  
+  curr = start + 2;
+  
+  if (SORT_CMP(dst[start], dst[start + 1]) <= 0)
+  {
+    /* increasing run */
+    while (1)
+    {
+      if (curr == size - 1) break;
+      if (SORT_CMP(dst[curr - 1], dst[curr]) > 0) break;
+      curr++;
+    }
+    return curr - start;    
+  }
+  else
+  {
+    /* decreasing run */
+    while (1)
+    {
+      if (curr == size - 1) break;
+      if (SORT_CMP(dst[curr - 1], dst[curr]) <= 0) break;
+      curr++;
+    }
+    /* reverse in-place */
+    REVERSE_ELEMENTS(dst, start, curr - 1);
+    return curr - start;
+  }
+}
+
+#define PUSH_NEXT() do {\
+len = COUNT_RUN(dst, curr, size);\
+run = minrun;\
+if (run < minrun) run = minrun;\
+if (run > size - curr) run = size - curr;\
+if (run > len)\
+{\
+  BINARY_INSERTION_SORT_START(&dst[curr], len, run);\
+  len = run;\
+}\
+{\
+run_stack[stack_curr].start = curr;\
+run_stack[stack_curr].length = len;\
+stack_curr++;\
+}\
+curr += len;\
+if (curr == size)\
+{\
+  /* finish up */ \
+  while (stack_curr > 1) \
+  { \
+    TIM_SORT_MERGE(dst, run_stack, stack_curr, store); \
+    run_stack[stack_curr - 2].length += run_stack[stack_curr - 1].length; \
+    stack_curr--; \
+  } \
+  if (store->storage != NULL)\
+  {\
+    free(store->storage);\
+    store->storage = NULL;\
+  }\
+  return;\
+}\
+}\
+while (0)
+  
+static int CHECK_INVARIANT(TIM_SORT_RUN_T *stack, const int stack_curr)
+{
+  int64_t A, B, C;
+  if (stack_curr < 2) return 1;
+  if (stack_curr == 2)
+  {
+    const int64_t A1 = stack[stack_curr - 2].length;
+    const int64_t B1 = stack[stack_curr - 1].length;
+    if (A1 <= B1) return 0;
+    return 1;
+  }
+  A = stack[stack_curr - 3].length;
+  B = stack[stack_curr - 2].length;
+  C = stack[stack_curr - 1].length;
+  if ((A <= B + C) || (B <= C)) return 0;
+  return 1;
+}
+
+typedef struct {
+  size_t alloc;
+  SORT_TYPE *storage;
+} TEMP_STORAGE_T;
+  
+
+static void TIM_SORT_RESIZE(TEMP_STORAGE_T *store, const size_t new_size)
+{
+  if (store->alloc < new_size)
+  {
+    SORT_TYPE *tempstore = (SORT_TYPE *)realloc(store->storage, new_size * sizeof(SORT_TYPE));
+    if (tempstore == NULL)
+    {
+      fprintf(stderr, "Error allocating temporary storage for tim sort: need %lu bytes", sizeof(SORT_TYPE) * new_size);
+      exit(1);
+    }
+    store->storage = tempstore;
+    store->alloc = new_size;
+  }
+}
+
+static void TIM_SORT_MERGE(SORT_TYPE *dst, const TIM_SORT_RUN_T *stack, const int stack_curr, TEMP_STORAGE_T *store)
+{
+  const int64_t A = stack[stack_curr - 2].length;
+  const int64_t B = stack[stack_curr - 1].length;
+  const int64_t curr = stack[stack_curr - 2].start;
+  SORT_TYPE *storage;
+  int64_t i, j, k;
+
+  TIM_SORT_RESIZE(store, MIN(A, B));
+  storage = store->storage;
+
+  /* left merge */
+  if (A < B)
+  {
+    memcpy(storage, &dst[curr], A * sizeof(SORT_TYPE));
+    i = 0;
+    j = curr + A;
+    
+    for (k = curr; k < curr + A + B; k++)
+    {
+      if ((i < A) && (j < curr + A + B))
+      {
+        if (SORT_CMP(storage[i], dst[j]) <= 0)
+          dst[k] = storage[i++];
+        else
+          dst[k] = dst[j++];          
+      }
+      else if (i < A)
+      {
+        dst[k] = storage[i++];
+      }
+      else
+        dst[k] = dst[j++];
+    }
+  }
+  /* right merge */
+  else
+  {    
+    memcpy(storage, &dst[curr + A], B * sizeof(SORT_TYPE));
+    i = B - 1;
+    j = curr + A - 1;
+    
+    for (k = curr + A + B - 1; k >= curr; k--)
+    {
+      if ((i >= 0) && (j >= curr))
+      {
+          if (SORT_CMP(dst[j], storage[i]) > 0)
+            dst[k] = dst[j--];
+          else
+            dst[k] = storage[i--];          
+      }
+      else if (i >= 0)
+        dst[k] = storage[i--];
+      else
+        dst[k] = dst[j--];
+    }
+  }
+}
+
+static int TIM_SORT_COLLAPSE(SORT_TYPE *dst, TIM_SORT_RUN_T *stack, int stack_curr, TEMP_STORAGE_T *store, const size_t size)
+{
+  while (1)
+  {
+  	int64_t A, B, C;
+    /* if the stack only has one thing on it, we are done with the collapse */
+    if (stack_curr <= 1) break;
+    /* if this is the last merge, just do it */
+    if ((stack_curr == 2) && (stack[0].length + stack[1].length == size))
+    {
+      TIM_SORT_MERGE(dst, stack, stack_curr, store);
+      stack[0].length += stack[1].length;
+      stack_curr--;
+      break;
+    }
+    /* check if the invariant is off for a stack of 2 elements */
+    else if ((stack_curr == 2) && (stack[0].length <= stack[1].length))
+    {
+      TIM_SORT_MERGE(dst, stack, stack_curr, store);
+      stack[0].length += stack[1].length;
+      stack_curr--;
+      break;
+    }
+    else if (stack_curr == 2)
+      break;
+      
+    A = stack[stack_curr - 3].length;
+    B = stack[stack_curr - 2].length;
+    C = stack[stack_curr - 1].length;
+    
+    /* check first invariant */
+    if (A <= B + C)
+    {
+      if (A < C)
+      {
+        TIM_SORT_MERGE(dst, stack, stack_curr - 1, store);
+        stack[stack_curr - 3].length += stack[stack_curr - 2].length;
+        stack[stack_curr - 2] = stack[stack_curr - 1];
+        stack_curr--;
+      }
+      else
+      {
+        TIM_SORT_MERGE(dst, stack, stack_curr, store);
+        stack[stack_curr - 2].length += stack[stack_curr - 1].length;
+        stack_curr--;
+      }
+    }
+    /* check second invariant */
+    else if (B <= C)
+    {
+      TIM_SORT_MERGE(dst, stack, stack_curr, store);
+      stack[stack_curr - 2].length += stack[stack_curr - 1].length;
+      stack_curr--;      
+    }
+    else
+      break;
+  }
+  return stack_curr;
+}
+
+void TIM_SORT(SORT_TYPE *dst, const size_t size)
+{
+	int minrun;
+	TEMP_STORAGE_T _store, *store;
+	TIM_SORT_RUN_T run_stack[128];
+	int stack_curr = 0;
+  int64_t len, run;
+  int64_t curr = 0;
+  
+  if (size < 64)
+  {
+    BINARY_INSERTION_SORT(dst, size);
+    return;
+  }
+  
+  /* compute the minimum run length */
+  minrun = compute_minrun(size);
+  
+  /* temporary storage for merges */
+  store = &_store;
+  store->alloc = 0;
+  store->storage = NULL;
+  
+  PUSH_NEXT();
+  PUSH_NEXT();
+  PUSH_NEXT();
+  
+  while (1)
+  {
+    if (!CHECK_INVARIANT(run_stack, stack_curr))
+    {
+      stack_curr = TIM_SORT_COLLAPSE(dst, run_stack, stack_curr, store, size);
+      continue;
+    }
+    PUSH_NEXT();
+  }
+}
+
+#undef SORT_CONCAT
+#undef SORT_MAKE_STR1
+#undef SORT_MAKE_STR
+#undef SORT_NAME
+#undef SORT_TYPE
+#undef SORT_CMP
+#undef TEMP_STORAGE_T
+#undef TIM_SORT_RUN_T
+#undef PUSH_NEXT
+#undef SORT_SWAP
+#undef SORT_CONCAT
+#undef SORT_MAKE_STR1
+#undef SORT_MAKE_STR
+#undef BINARY_INSERTION_FIND
+#undef BINARY_INSERTION_SORT_START
+#undef BINARY_INSERTION_SORT
+#undef REVERSE_ELEMENTS
+#undef COUNT_RUN
+#undef TIM_SORT
+#undef TIM_SORT_RESIZE
+#undef TIM_SORT_COLLAPSE
+#undef TIM_SORT_RUN_T
+#undef TEMP_STORAGE_T
+
+
diff --git c/win32/Makefile.bcb w/win32/Makefile.bcb
index d612e2d..302e815 100644
--- c/win32/Makefile.bcb
+++ w/win32/Makefile.bcb
@@ -137,6 +137,7 @@ XML_OBJS = $(XML_INTDIR)\c14n.obj\
 	$(XML_INTDIR)\SAX.obj\
 	$(XML_INTDIR)\SAX2.obj\
 	$(XML_INTDIR)\schematron.obj\
+	$(XML_INTDIR)\sort.obj\
 	$(XML_INTDIR)\threads.obj\
 	$(XML_INTDIR)\tree.obj\
 	$(XML_INTDIR)\uri.obj\
@@ -182,6 +183,7 @@ XML_OBJS_A = $(XML_INTDIR_A)\c14n.obj\
 	$(XML_INTDIR_A)\SAX.obj\
 	$(XML_INTDIR_A)\SAX2.obj\
 	$(XML_INTDIR_A)\schematron.obj\
+	$(XML_INTDIR_A)\sort.obj\
 	$(XML_INTDIR_A)\threads.obj\
 	$(XML_INTDIR_A)\tree.obj\
 	$(XML_INTDIR_A)\uri.obj\
diff --git c/win32/Makefile.mingw w/win32/Makefile.mingw
index 0f8198b..f7bd628 100644
--- c/win32/Makefile.mingw
+++ w/win32/Makefile.mingw
@@ -131,6 +131,7 @@ XML_OBJS = $(XML_INTDIR)/c14n.o\
 	$(XML_INTDIR)/SAX.o\
 	$(XML_INTDIR)/SAX2.o\
 	$(XML_INTDIR)/schematron.o\
+	$(XML_INTDIR)\sort.o\
 	$(XML_INTDIR)/threads.o\
 	$(XML_INTDIR)/tree.o\
 	$(XML_INTDIR)/uri.o\
@@ -178,6 +179,7 @@ XML_OBJS_A = $(XML_INTDIR_A)/c14n.o\
 	$(XML_INTDIR_A)/SAX.o\
 	$(XML_INTDIR_A)/SAX2.o\
 	$(XML_INTDIR_A)/schematron.o\
+	$(XML_INTDIR_A)\sort.o\
 	$(XML_INTDIR_A)/threads.o\
 	$(XML_INTDIR_A)/tree.o\
 	$(XML_INTDIR_A)/uri.o\
diff --git c/win32/Makefile.msvc w/win32/Makefile.msvc
index cc93372..c328009 100644
--- c/win32/Makefile.msvc
+++ w/win32/Makefile.msvc
@@ -132,6 +132,7 @@ XML_OBJS = $(XML_INTDIR)\c14n.obj\
 	$(XML_INTDIR)\SAX2.obj\
 	$(XML_INTDIR)\SAX.obj\
 	$(XML_INTDIR)\schematron.obj\
+	$(XML_INTDIR)\sort.obj\
 	$(XML_INTDIR)\threads.obj\
 	$(XML_INTDIR)\tree.obj\
 	$(XML_INTDIR)\uri.obj\
@@ -177,6 +178,7 @@ XML_OBJS_A = $(XML_INTDIR_A)\c14n.obj\
 	$(XML_INTDIR_A)\SAX2.obj\
 	$(XML_INTDIR_A)\SAX.obj\
 	$(XML_INTDIR_A)\schematron.obj\
+	$(XML_INTDIR_A)\sort.obj\
 	$(XML_INTDIR_A)\threads.obj\
 	$(XML_INTDIR_A)\tree.obj\
 	$(XML_INTDIR_A)\uri.obj\
@@ -222,6 +224,7 @@ XML_OBJS_A_DLL = $(XML_INTDIR_A_DLL)\c14n.obj\
 	$(XML_INTDIR_A_DLL)\SAX2.obj\
 	$(XML_INTDIR_A_DLL)\SAX.obj\
 	$(XML_INTDIR_A_DLL)\schematron.obj\
+	$(XML_INTDIR_A_DLL)\sort.obj\
 	$(XML_INTDIR_A_DLL)\threads.obj\
 	$(XML_INTDIR_A_DLL)\tree.obj\
 	$(XML_INTDIR_A_DLL)\uri.obj\
diff --git c/win32/Makefile.msvc.withpdb w/win32/Makefile.msvc.withpdb
index 060a3f9..075feb4 100644
--- c/win32/Makefile.msvc.withpdb
+++ w/win32/Makefile.msvc.withpdb
@@ -122,6 +122,7 @@ XML_OBJS = $(XML_INTDIR)\c14n.obj\
 	$(XML_INTDIR)\SAX2.obj\
 	$(XML_INTDIR)\SAX.obj\
 	$(XML_INTDIR)\schematron.obj\
+	$(XML_INTDIR)\sort.obj\
 	$(XML_INTDIR)\threads.obj\
 	$(XML_INTDIR)\tree.obj\
 	$(XML_INTDIR)\uri.obj\
@@ -167,6 +168,7 @@ XML_OBJS_A = $(XML_INTDIR_A)\c14n.obj\
 	$(XML_INTDIR_A)\SAX2.obj\
 	$(XML_INTDIR_A)\SAX.obj\
 	$(XML_INTDIR_A)\schematron.obj\
+	$(XML_INTDIR_A)\sort.obj\
 	$(XML_INTDIR_A)\threads.obj\
 	$(XML_INTDIR_A)\tree.obj\
 	$(XML_INTDIR_A)\uri.obj\
@@ -212,6 +214,7 @@ XML_OBJS_A_DLL = $(XML_INTDIR_A_DLL)\c14n.obj\
 	$(XML_INTDIR_A_DLL)\SAX2.obj\
 	$(XML_INTDIR_A_DLL)\SAX.obj\
 	$(XML_INTDIR_A_DLL)\schematron.obj\
+	$(XML_INTDIR_A_DLL)\sort.obj\
 	$(XML_INTDIR_A_DLL)\threads.obj\
 	$(XML_INTDIR_A_DLL)\tree.obj\
 	$(XML_INTDIR_A_DLL)\uri.obj\
diff --git c/win32/VC10/libxml2-focus.vcxproj w/win32/VC10/libxml2-focus.vcxproj
index 914ce25..95d36e1 100644
--- c/win32/VC10/libxml2-focus.vcxproj
+++ w/win32/VC10/libxml2-focus.vcxproj
@@ -150,6 +150,7 @@
     <ClCompile Include="..\..\relaxng.c" />
     <ClCompile Include="..\..\SAX.c" />
     <ClCompile Include="..\..\SAX2.c" />
+    <ClCompile Include="..\..\sort.c" />
     <ClCompile Include="..\..\schematron.c" />
     <ClCompile Include="..\..\threads.c" />
     <ClCompile Include="..\..\tree.c" />
diff --git c/win32/VC10/libxml2.vcxproj w/win32/VC10/libxml2.vcxproj
index 0d5a1bc..6953f63 100644
--- c/win32/VC10/libxml2.vcxproj
+++ w/win32/VC10/libxml2.vcxproj
@@ -93,6 +93,7 @@
     <ClCompile Include="..\..\SAX.c" />
     <ClCompile Include="..\..\SAX2.c" />
     <ClCompile Include="..\..\schematron.c" />
+    <ClCompile Include="..\..\sort.c" />
     <ClCompile Include="..\..\threads.c" />
     <ClCompile Include="..\..\tree.c" />
     <ClCompile Include="..\..\uri.c" />
diff --git c/win32/VC10/libxml2.vcxproj.filters w/win32/VC10/libxml2.vcxproj.filters
index e8e7af3..25254c7 100644
--- c/win32/VC10/libxml2.vcxproj.filters
+++ w/win32/VC10/libxml2.vcxproj.filters
@@ -81,6 +81,9 @@
     <ClCompile Include="..\..\schematron.c">
       <Filter>Source Files</Filter>
     </ClCompile>
+    <ClCompile Include="..\..\sort.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
     <ClCompile Include="..\..\threads.c">
       <Filter>Source Files</Filter>
     </ClCompile>
diff --git c/xpath.c w/xpath.c
index d9d902c..6cd54ed 100644
--- c/xpath.c
+++ w/xpath.c
@@ -65,17 +65,6 @@
             __FILE__, __LINE__);
 
 /*
-* XP_OPTIMIZED_NON_ELEM_COMPARISON:
-* If defined, this will use xmlXPathCmpNodesExt() instead of
-* xmlXPathCmpNodes(). The new function is optimized comparison of
-* non-element nodes; actually it will speed up comparison only if
-* xmlXPathOrderDocElems() was called in order to index the elements of
-* a tree in document order; Libxslt does such an indexing, thus it will
-* benefit from this optimization.
-*/
-#define XP_OPTIMIZED_NON_ELEM_COMPARISON
-
-/*
 * XP_OPTIMIZED_FILTER_FIRST:
 * If defined, this will optimize expressions like "key('foo', 'val')[b][1]"
 * in a way, that it stop evaluation at the first node.
@@ -3032,7 +3021,7 @@ xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2) {
  * Returns -2 in case of error 1 if first point < second point, 0 if
  *         it's the same node, -1 otherwise
  */
-static int
+int
 xmlXPathCmpNodesExt(xmlNodePtr node1, xmlNodePtr node2) {
     int depth1, depth2;
     int misc = 0, precedence1 = 0, precedence2 = 0;
@@ -3320,35 +3309,13 @@ turtle_comparison:
  */
 void
 xmlXPathNodeSetSort(xmlNodeSetPtr set) {
-    int i, j, incr, len;
-    xmlNodePtr tmp;
+    int len;
 
     if (set == NULL)
-	return;
+        return;
 
-    /* Use Shell's sort to sort the node-set */
     len = set->nodeNr;
-    for (incr = len / 2; incr > 0; incr /= 2) {
-	for (i = incr; i < len; i++) {
-	    j = i - incr;
-	    while (j >= 0) {
-#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
-		if (xmlXPathCmpNodesExt(set->nodeTab[j],
-			set->nodeTab[j + incr]) == -1)
-#else
-		if (xmlXPathCmpNodes(set->nodeTab[j],
-			set->nodeTab[j + incr]) == -1)
-#endif
-		{
-		    tmp = set->nodeTab[j];
-		    set->nodeTab[j] = set->nodeTab[j + incr];
-		    set->nodeTab[j + incr] = tmp;
-		    j -= incr;
-		} else
-		    break;
-	    }
-	}
-    }
+    xmlNodeTimSort(set->nodeTab, len);
 }
 
 #define XML_NODESET_DEFAULT	10
