-
-
Save VardanGrigoryan/8369757 to your computer and use it in GitHub Desktop.
Ինչպիսի՞ տվյալների կառուցվածք է առավել հաճախ օգտագործվում նախապատվություններով հերթի կառուցման դեպքում:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class heap | |
{ | |
private: | |
int size; | |
private: | |
int get_left(int i); | |
int get_rigth(int i); | |
int get_parent(int i); | |
void swap(int& x, int& y); | |
void heapify(int* a, int s, int n); | |
int* build_heap(int* a, int s); | |
public: | |
heap() {} | |
int* heap_sort(int* a, int s); | |
int* shift_rigth(int* a, int& s); | |
void print_heap(int* a, int s); | |
}; | |
int heap::get_left(int i) | |
{ | |
return 2*i; | |
} | |
int heap::get_rigth(int i) | |
{ | |
return 2*i + 1; | |
} | |
int heap::get_parent(int i) | |
{ | |
return i/2; | |
} | |
void heap::swap(int& x, int& y) | |
{ | |
int t = x; | |
x = y; | |
y = t; | |
} | |
void heap::heapify(int* a, int s, int n) | |
{ | |
int l = get_left(n); | |
int r = get_rigth(n); | |
int m; | |
if(l <= s && a[l] > a[n]) | |
{ | |
m = l; | |
} | |
else | |
{ | |
m = n; | |
} | |
if(r <= s && a[r] > a[m]) | |
{ | |
m = r; | |
} | |
if(m != n) | |
{ | |
swap(a[m], a[n]); | |
heapify(a, s, m); | |
} | |
} | |
int* heap::build_heap(int* a, int s) | |
{ | |
for(int i = s/2; i >= 1 ; --i) | |
{ | |
heapify(a, s, i); | |
} | |
} | |
int* heap::heap_sort(int* a, int s) | |
{ | |
build_heap(a, s); | |
for(int i = s; i >= 2 ; --i) | |
{ | |
swap(a[1], a[i]); | |
--s; | |
heapify(a, s, 1); | |
} | |
return a; | |
} | |
// զուտ լեզվի տեսանկյունից ճիշտ կլինի ֆունկցիաներում ստեղծված և հիշողություն հատկացված լոկալ ցուցիչները (heap -յաին փոփոխականները) դնել որևիցե smart ptr-ի մեջ memory leek-ից խուսափելու համար։ | |
int* heap::shift_rigth(int a[], int& s) | |
{ | |
int* b = new int[s]; | |
for(int i = 0; i < s; ++i) | |
{ | |
b[i + 1] = a[i]; | |
} | |
return b; | |
} | |
void heap::print_heap(int* a, int s) | |
{ | |
for(int i = 1; i <= s; ++i) | |
{ | |
std::cout << a[i] << " "; | |
} | |
std::cout << std::endl; | |
} | |
int main() | |
{ | |
heap h; | |
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7}; | |
int s = (sizeof(a)/sizeof(a[0])); | |
// heap-ի գագաթը միշտ հանդիսանում է 1 ինդեքսով տարրը, այլ ոչ թե զրո, դրա համար կանչում են shift_rigth ֆունկցիան և մուտքային զանգվածը փոփոխում ենք այնպես, որ ինդեքսավորումը սկսվի 1-ից։ | |
int* b = h.shift_rigth(a, s); | |
int* r = h.heap_sort(b, s); | |
h.print_heap(r, s); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment