Timsort saralash (Timsort)




Download 1,92 Mb.
bet78/131
Sana16.06.2024
Hajmi1,92 Mb.
#264063
1   ...   74   75   76   77   78   79   80   81   ...   131
Bog'liq
Tiplarni dinamik tarzda

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);



s.push(z);
s.push(make_pair(x.first + y.first, y.second));
}
else {
merge(z.second, y.second, y.second + y.first, temp); s.push(make_pair( z.first + y.first, z.second )); s.push(x);
}
}
while (s.size() != 1) {
pair x = s.top(); s.pop();
pair y = s.top(); s.pop();
if (x.second < y.second) swap(x, y);
merge(y.second, x.second, x.second + x.first, temp); s.push(make_pair( y.first + x.first, y.second ));
}
}
}
void timsort(int* l, int* r) { int* temp = new int[r - l];
_timsort(l, r, temp); delete temp;
}

Yuqorida 16 ta saralash algoritmlarni hosil qilish va tayyo dasturiy fragmentlari keltirildi.

Download 1,92 Mb.
1   ...   74   75   76   77   78   79   80   81   ...   131




Download 1,92 Mb.