uarrsort.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. *******************************************************************************
  5. *
  6. * Copyright (C) 2003-2013, International Business Machines
  7. * Corporation and others. All Rights Reserved.
  8. *
  9. *******************************************************************************
  10. * file name: uarrsort.c
  11. * encoding: UTF-8
  12. * tab size: 8 (not used)
  13. * indentation:4
  14. *
  15. * created on: 2003aug04
  16. * created by: Markus W. Scherer
  17. *
  18. * Internal function for sorting arrays.
  19. */
  20. #include <cstddef>
  21. #include "unicode/utypes.h"
  22. #include "cmemory.h"
  23. #include "uarrsort.h"
  24. enum {
  25. /**
  26. * "from Knuth"
  27. *
  28. * A binary search over 8 items performs 4 comparisons:
  29. * log2(8)=3 to subdivide, +1 to check for equality.
  30. * A linear search over 8 items on average also performs 4 comparisons.
  31. */
  32. MIN_QSORT=9,
  33. STACK_ITEM_SIZE=200
  34. };
  35. static constexpr int32_t sizeInMaxAlignTs(int32_t sizeInBytes) {
  36. return (sizeInBytes + sizeof(std::max_align_t) - 1) / sizeof(std::max_align_t);
  37. }
  38. /* UComparator convenience implementations ---------------------------------- */
  39. U_CAPI int32_t U_EXPORT2
  40. uprv_uint16Comparator(const void *context, const void *left, const void *right) {
  41. (void)context;
  42. return (int32_t)*(const uint16_t *)left - (int32_t)*(const uint16_t *)right;
  43. }
  44. U_CAPI int32_t U_EXPORT2
  45. uprv_int32Comparator(const void *context, const void *left, const void *right) {
  46. (void)context;
  47. return *(const int32_t *)left - *(const int32_t *)right;
  48. }
  49. U_CAPI int32_t U_EXPORT2
  50. uprv_uint32Comparator(const void *context, const void *left, const void *right) {
  51. (void)context;
  52. uint32_t l=*(const uint32_t *)left, r=*(const uint32_t *)right;
  53. /* compare directly because (l-r) would overflow the int32_t result */
  54. if(l<r) {
  55. return -1;
  56. } else if(l==r) {
  57. return 0;
  58. } else /* l>r */ {
  59. return 1;
  60. }
  61. }
  62. /* Insertion sort using binary search --------------------------------------- */
  63. U_CAPI int32_t U_EXPORT2
  64. uprv_stableBinarySearch(char *array, int32_t limit, void *item, int32_t itemSize,
  65. UComparator *cmp, const void *context) {
  66. int32_t start=0;
  67. UBool found=false;
  68. /* Binary search until we get down to a tiny sub-array. */
  69. while((limit-start)>=MIN_QSORT) {
  70. int32_t i=(start+limit)/2;
  71. int32_t diff=cmp(context, item, array+i*itemSize);
  72. if(diff==0) {
  73. /*
  74. * Found the item. We look for the *last* occurrence of such
  75. * an item, for stable sorting.
  76. * If we knew that there will be only few equal items,
  77. * we could break now and enter the linear search.
  78. * However, if there are many equal items, then it should be
  79. * faster to continue with the binary search.
  80. * It seems likely that we either have all unique items
  81. * (where found will never become true in the insertion sort)
  82. * or potentially many duplicates.
  83. */
  84. found=true;
  85. start=i+1;
  86. } else if(diff<0) {
  87. limit=i;
  88. } else {
  89. start=i;
  90. }
  91. }
  92. /* Linear search over the remaining tiny sub-array. */
  93. while(start<limit) {
  94. int32_t diff=cmp(context, item, array+start*itemSize);
  95. if(diff==0) {
  96. found=true;
  97. } else if(diff<0) {
  98. break;
  99. }
  100. ++start;
  101. }
  102. return found ? (start-1) : ~start;
  103. }
  104. static void
  105. doInsertionSort(char *array, int32_t length, int32_t itemSize,
  106. UComparator *cmp, const void *context, void *pv) {
  107. int32_t j;
  108. for(j=1; j<length; ++j) {
  109. char *item=array+j*itemSize;
  110. int32_t insertionPoint=uprv_stableBinarySearch(array, j, item, itemSize, cmp, context);
  111. if(insertionPoint<0) {
  112. insertionPoint=~insertionPoint;
  113. } else {
  114. ++insertionPoint; /* one past the last equal item */
  115. }
  116. if(insertionPoint<j) {
  117. char *dest=array+insertionPoint*itemSize;
  118. uprv_memcpy(pv, item, itemSize); /* v=array[j] */
  119. uprv_memmove(dest+itemSize, dest, (j-insertionPoint)*(size_t)itemSize);
  120. uprv_memcpy(dest, pv, itemSize); /* array[insertionPoint]=v */
  121. }
  122. }
  123. }
  124. static void
  125. insertionSort(char *array, int32_t length, int32_t itemSize,
  126. UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
  127. icu::MaybeStackArray<std::max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE)> v;
  128. if (sizeInMaxAlignTs(itemSize) > v.getCapacity() &&
  129. v.resize(sizeInMaxAlignTs(itemSize)) == nullptr) {
  130. *pErrorCode = U_MEMORY_ALLOCATION_ERROR;
  131. return;
  132. }
  133. doInsertionSort(array, length, itemSize, cmp, context, v.getAlias());
  134. }
  135. /* QuickSort ---------------------------------------------------------------- */
  136. /*
  137. * This implementation is semi-recursive:
  138. * It recurses for the smaller sub-array to shorten the recursion depth,
  139. * and loops for the larger sub-array.
  140. *
  141. * Loosely after QuickSort algorithms in
  142. * Niklaus Wirth
  143. * Algorithmen und Datenstrukturen mit Modula-2
  144. * B.G. Teubner Stuttgart
  145. * 4. Auflage 1986
  146. * ISBN 3-519-02260-5
  147. */
  148. static void
  149. subQuickSort(char *array, int32_t start, int32_t limit, int32_t itemSize,
  150. UComparator *cmp, const void *context,
  151. void *px, void *pw) {
  152. int32_t left, right;
  153. /* start and left are inclusive, limit and right are exclusive */
  154. do {
  155. if((start+MIN_QSORT)>=limit) {
  156. doInsertionSort(array+start*itemSize, limit-start, itemSize, cmp, context, px);
  157. break;
  158. }
  159. left=start;
  160. right=limit;
  161. /* x=array[middle] */
  162. uprv_memcpy(px, array+(size_t)((start+limit)/2)*itemSize, itemSize);
  163. do {
  164. while(/* array[left]<x */
  165. cmp(context, array+left*itemSize, px)<0
  166. ) {
  167. ++left;
  168. }
  169. while(/* x<array[right-1] */
  170. cmp(context, px, array+(right-1)*itemSize)<0
  171. ) {
  172. --right;
  173. }
  174. /* swap array[left] and array[right-1] via w; ++left; --right */
  175. if(left<right) {
  176. --right;
  177. if(left<right) {
  178. uprv_memcpy(pw, array+(size_t)left*itemSize, itemSize);
  179. uprv_memcpy(array+(size_t)left*itemSize, array+(size_t)right*itemSize, itemSize);
  180. uprv_memcpy(array+(size_t)right*itemSize, pw, itemSize);
  181. }
  182. ++left;
  183. }
  184. } while(left<right);
  185. /* sort sub-arrays */
  186. if((right-start)<(limit-left)) {
  187. /* sort [start..right[ */
  188. if(start<(right-1)) {
  189. subQuickSort(array, start, right, itemSize, cmp, context, px, pw);
  190. }
  191. /* sort [left..limit[ */
  192. start=left;
  193. } else {
  194. /* sort [left..limit[ */
  195. if(left<(limit-1)) {
  196. subQuickSort(array, left, limit, itemSize, cmp, context, px, pw);
  197. }
  198. /* sort [start..right[ */
  199. limit=right;
  200. }
  201. } while(start<(limit-1));
  202. }
  203. static void
  204. quickSort(char *array, int32_t length, int32_t itemSize,
  205. UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
  206. /* allocate two intermediate item variables (x and w) */
  207. icu::MaybeStackArray<std::max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE) * 2> xw;
  208. if(sizeInMaxAlignTs(itemSize)*2 > xw.getCapacity() &&
  209. xw.resize(sizeInMaxAlignTs(itemSize) * 2) == nullptr) {
  210. *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
  211. return;
  212. }
  213. subQuickSort(array, 0, length, itemSize, cmp, context,
  214. xw.getAlias(), xw.getAlias() + sizeInMaxAlignTs(itemSize));
  215. }
  216. /* uprv_sortArray() API ----------------------------------------------------- */
  217. /*
  218. * Check arguments, select an appropriate implementation,
  219. * cast the array to char * so that array+i*itemSize works.
  220. */
  221. U_CAPI void U_EXPORT2
  222. uprv_sortArray(void *array, int32_t length, int32_t itemSize,
  223. UComparator *cmp, const void *context,
  224. UBool sortStable, UErrorCode *pErrorCode) {
  225. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  226. return;
  227. }
  228. if((length>0 && array==nullptr) || length<0 || itemSize<=0 || cmp==nullptr) {
  229. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  230. return;
  231. }
  232. if(length<=1) {
  233. return;
  234. } else if(length<MIN_QSORT || sortStable) {
  235. insertionSort((char *)array, length, itemSize, cmp, context, pErrorCode);
  236. } else {
  237. quickSort((char *)array, length, itemSize, cmp, context, pErrorCode);
  238. }
  239. }