本文共 2324 字,大约阅读时间需要 7 分钟。
Tim Sort是一种结合插入排序和归并排序的混合排序算法,最初为Python设计,后被Java的Arrays.sort()采用。它通过将数组划分为小块(称为“运行”),对每个运行进行排序,然后合并运行以实现高效排序。
Tim Sort的核心思想是将数组分成多个小块(默认为32个运行),每个运行单独进行插入排序。完成后,合并这些有序的运行,逐步生成最终的有序数组。
#import#define RUN 32void timSort(void *array, size_t n) { if (n <= 1) { return; } size_t size = n; size_t minRunLength = RUN; size_t maxRunLength = n; while (minRunLength <= maxRunLength) { size_t length = n - minRunLength; size_t run = minRunLength + length; if (run > maxRunLength) { run = maxRunLength; length = n - run; } void *sub = (void *)(array + minRunLength); void *end = (void *)(array + run); if (minRunLength == 0) { if (maxRunLength == 0) { break; } void (*cmp)(void *, void *, int *) = memcmp; memcpy(end, sub, length); minRunLength++; maxRunLength--; continue; } void *base = sub; void *current = base; void *end = (void *)(array + run); if (maxRunLength != 0) { void (*cmp)(void *, void *, int *) = memcmp; void *last = end; while (current < end) { size_t next = current + minRunLength; if (next > end) { next = end; } int cmp = cmp(current, next, NULL); if (cmp != 0) { memcpy(current + minRunLength, last, (size_t)(last - current)); last = current; } current = next; } memcpy(last, current, (size_t)(end - last)); maxRunLength--; } else { void (*cmp)(void *, void *, int *) = qsort; qsort(base, run, minRunLength, end); } memcpy(base, current, (size_t)(end - current)); minRunLength++; maxRunLength--; }}
timSort对传入的数组进行排序。Tim Sort通过将大数组划分为小块,减少了每次排序操作的时间和空间复杂度,使其在实际应用中表现优异。
转载地址:http://ekifk.baihongyu.com/