קודם כל ממיינים את המערך הפעולה עולה n log n אח"כ סורקים מהסוף להתחלה ולכל מספר מבצעים חיפוש בינארי במערך בגודל 0..i-1 בחיפוש בודקים אם כל מספר בריבוע גדול מהמספר במיקום i קטן ממנו או שווה לו פעולה זה עולה גם כן n log n בסה"כ שתיי סריקות n log n ולכן הסיבוכיות היא o(n log n)
לא אמרתי שמערך לא יכול לייצג ערמה. אמרתי כי המערך שנתתי לא בהכרח מייצג ערמה במצבו הנוכחי ולכן עליך לעשות עליו מניפולציה על מנת להעביר אותו לערמה תקנית, מה שידרוש בהכרח עוד מערך עזר.
אם תרצה הרחבה לגבי ערמה ( heapify...) או משהו אחר אשמח לעזור...
void heapsort(int arr, unsigned int N) { unsigned int n = N, i = n/2, parent, child; int t;
for (;;) { /* Loops until arr is sorted */ if (i > 0) { /* First stage - Sorting the heap */ i--; /* Save its index to i */ t = arr; /* Save parent value to t */ } else { /* Second stage - Extracting elements in-place */ n--; /* Make the new heap smaller */ if (n == 0) return; /* When the heap is empty, we are done */ t = arr; /* Save last value (it will be overwritten) */ arr = arr; /* Save largest value at the end of arr */ }
parent = i; /* We will start pushing down t from parent */ child = i*2 + 1; /* parent's left child */
/* Sift operation - pushing the value of t down the heap */ while (child < n) { if (child + 1 < n && arr > arr) { child++; /* Choose the largest child */ } if (arr > t) { /* If any child is bigger than the parent */ arr = arr; /* Move the largest child up */ parent = child; /* Move parent pointer to this child */ child = parent*2 + 1; /* Find the next child */ } else { break; /* t's place is found */ } } arr = t; /* We save t in the heap */ } }
מה שאומר שכל אב גדול מבניו. כלומר לאינדקס i הבן השמאלי 2*i והבן הימני 2*i + 1 קטנים ממנו.. רק אז תוכל להריץ heapsort על המערך אחרת אין שום משמעות ל Heapsort.
במצב הנוכחי יכול להיות במערך שנתתי מצב בו האב אינו גדול מבניו ואז מיון ערמה כמובן לא יבצע מיון.