我的任務是根據僞代碼將代碼寫入heapsort。它應該排列輸入數組(4 3 2 5 6 7 8 9 12 1
),然後使用printHeap方法打印它。我知道printHeap的工作原理,因爲我已經使用了一個名爲buildHeap的方法(構建最大堆二叉樹,但你們都已經知道:)),並且它的工作原理完美無誤,所以我的問題在於heapSort 。HeapSort問題
它排序正確,並以它應該的方式打印它(父 - 子1,父 - 2等),唯一的問題是,最大值和最後一個值是12,突然變成24,我不知道爲什麼。
的代碼如下:
void heapSort(int a[], int n){
int x = n+1;
int i;
int temp;
buildMaxHeap(a, n);
for (i = n; i >= 1; i--){
temp = a[i];
a[i] = a [0];
a [0] = temp;
x--;
heapify(a, 0, x);
}
void printHeap(int a[], int n){
int i;
printf("graph g { \n");
for (i = 0; i < n/2; i++){
printf("%d -- %d\n", a[i], a[left(i)]);
if (right(i) < n){
printf("%d -- %d\n", a[i], a[right(i)]);
}
}
printf("}\n");
輸出爲以下內容:只要你知道究竟是什麼我也做
1 2 3 4 5 6 7 8 9 24
graph g {
1 -- 2
1 -- 3
2 -- 4
2 -- 5
3 -- 6
3 -- 7
4 -- 8
4 -- 9
5 -- 24
}
,我會附上而.C這裏提交: https://onedrive.live.com/redir?resid=8BC629F201D2BC63!26268&authkey=!AFqVlm9AptiZ_xM&ithint=file%2cc
真的非常感謝您的幫助!
乾杯 阿里克
我沒有理由認爲你的'heapSort()'函數會導致數組中包含的值發生改變,儘管你沒有提供完整的代碼(你希望我們考慮的任何代碼應該在*自問*)。我建議你使用調試器來解決這個問題,但是如果你需要我們的幫助,那麼我們通常喜歡看[mcve]。 –
在'buildMaxHeap'中,您將一個索引'i'用於數組'a',其值可以高達'n'。如果'a'包含'n'值,那麼'i'不應該超過'n-1'。 –
當您輸入源數據時,您的計數器'n'從零開始,並在輸入每個數字後遞增。如果你輸入十個數字,它們被輸入到數組元素0到9中,但是n是10.在退出while循環後添加'n - ;'。現在使用'i <= n;'修正printArray循環控制,最後糾正printHeap循環控制'i <(n + 1)/ 2;'。 – anita2R