Timsort saralash (Timsort). Bu gibrid saralash hisoblanadi, qo‘shish orqali saralash va birlashtirish orqali saralash algoritmlaridan foydalanib yaratilgan. Massiv elementlarini bir necha kichik massivlarga ajratamiz va undagi elementlarni tartiblangan holda massiv ostiga kengaytiramiz. Tartiblangan massivlar ustida samarali ishlashidan foydalanib, massiv ostilarni joylashtirib tartiblash yo‘li bilan tartiblaymiz. Keyinchalik massiv ostilarni taxminan teng kattalikda olib, birilashtirish (merge) saralashdagi kabi birlashtiramiz (aks holda saralash vaqti kvadratga yaqinlashadi). Buning uchun massiv ostilarni invariant saqlab, stekka saqlash qulay — tepadan uzoqlashgan sari kattalashib boradi va uchinchi massiv ostining o‘lchami ularning kattaliklari yig‘indisidan katta yoki teng bo‘lgandagina yuqori qismida massiv ostilarni birlashtiradi. murakkabligi O(n) eng yaxshi holatda va O(nlogn) o‘rtacha va eng yomon holatda. Amalga oshirish arzimas va unga qatʻiy ishonch yo‘q, lekin u juda yaxshi saralash vaqti ko‘rsatdi.
8.16-dastur. Saralashni amalga oshirish.
void _timsort(int* l, int* r, int* temp) { int sz = r - l;
if (sz <= 64) {
insertionsort(l, r); return;
}
int minrun = sz, f = 0; while (minrun >= 64) {
f |= minrun & 1; minrun >>= 1;
}
minrun += f; int* cur = l;
stack
int*>> s; while (cur < r) {
int* c1 = cur;
while (c1 < r - 1 && *c1 <= *(c1 + 1)) c1++; int* c2 = cur;
while (c2 < r - 1 && *c2 >= *(c2 + 1)) c2++; if (c1 >= c2) {
c1 = max(c1, cur + minrun - 1); c1 = min(c1, r - 1); insertionsort(cur, c1 + 1);
s.push(make_pair(c1 - cur + 1, cur)); cur = c1 + 1;
}
else {
c2 = max(c2, cur + minrun - 1); c2 = min(c2, r - 1); reverse(cur, c2 + 1); insertionsort(cur, c2 + 1);
s.push(make_pair(c2 - cur + 1, cur)); cur = c2 + 1;
}
while (s.size() >= 3) {
pair x = s.top(); s.pop();
pair y = s.top(); s.pop();
pair z = s.top(); s.pop();
if (z.first >= x.first + y.first && y.first >= x.first) { s.push(z);
s.push(y);
s.push(x); break;
}
else if (z.first >= x.first + y.first) {
merge(y.second, x.second, x.second + x.first, temp);